我是python的新手,我每年都有一份年份和价值清单.我想要做的是检查字典中是否已存在年份,如果存在,则将值附加到特定键的值列表中.
例如,我有一个年份列表,每年有一个值:
2010
2
2009
4
1989
8
2009
7
Run Code Online (Sandbox Code Playgroud)
我想要做的是填充一个字典,其中年份为键,单个数字数字为值.但是,如果我有2009年列出两次,我想将第二个值附加到该字典中的值列表中,所以我希望:
2010: 2
2009: 4, 7
1989: 8
Run Code Online (Sandbox Code Playgroud)
现在我有以下内容:
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
Run Code Online (Sandbox Code Playgroud)