python字典中给一个键增加值_在Python字典中为一个键附加多个值

I am new to python and I have a list of years and values for each year. What I want to do is check if the year already exists in a dictionary and if it does, append the value to that list of values for the specific key.

So for instance, I have a list of years and have one value for each year:

2010

2

2009

4

1989

8

2009

7

What I want to do is populate a dictionary with the years as keys and those single digit numbers as values. However, if I have 2009 listed twice, I want to append that second value to my list of values in that dictionary, so I want:

2010: 2

2009: 4, 7

1989: 8

Right now I have the following:

d = dict()

years = []

(get 2 column list of years and values)

for line in list:

year = line[0]

value = line[1]

for line in list:

if year in d.keys():

d[value].append(value)

else:

d[value] = value

d[year] = year

解决方案

If I can rephrase your question, what you want is a dictionary with the years as keys and an array for each year containing a list of values associated with that year, right? Here's how I'd do it:

years_dict = dict()

for line in list:

if line[0] in years_dict:

# append the new number to the existing array at this slot

years_dict[line[0]].append(line[1])

else:

# create a new array in this slot

years_dict[line[0]] = [line[1]]

What you should end up with in years_dict is a dictionary that looks like the following:

{

"2010": [2],

"2009": [4,7],

"1989": [8]

}

In general, it's poor programming practice to create "parallel arrays", where items are implicitly associated with each other by having the same index rather than being proper children of a container that encompasses them both.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值