在字典中为一个键附加多个值 [英] append multiple values for one key in a dictionary
问题描述
我是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
我想做的是用年作为键填充那些字典,将那些数字作为值填充字典.但是,如果我两次列出了2009,那么我要将第二个值附加到该词典中的值列表中,所以我想:
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
现在我有以下内容:
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]]
在years_dict中应该得到的是一本类似于以下内容的字典:
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.
这篇关于在字典中为一个键附加多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!