【发布时间】:2021-06-30 11:24:33
【问题描述】:
问题在于我的列表年份,如您所见,有些值重复,如 1932、1933、1961...:
years = [1924, 1928, 1932, 1932, 1933, 1933, 1935, 1938, 1953, 1955, 1961, 1961, 1967, 1969, 1971, 1977, 1979, 1980, 1988, 1989, 1992, 1998, 2003, 2004, 2005, 2005, 2005, 2005, 2007, 2007, 2016, 2017, 2017, 2018]
所以我的职责是创建一个函数来遍历我的所有列表(所有列表都是 len 34),但我的输出只返回字典,其中只有一个重复年份,所以我的结果输出是 26 len 而不是 34
def dictionary_maker2(names, months, years, max_sustained_winds, areas_affected, list_update_damage, deaths):
for n in range(len(years)):
hurricanes_year[years[n]] = {'Names': names[n], 'Month': months[n], 'Year': years[n],
'Max Sustained Wind': max_sustained_winds[n], 'Areas Affected': areas_affected[n],
'Damage': list_update_damage[n], 'Deaths': deaths[n]}
如果我没有使用正确的方式在 stackoverflow 中提问,请告诉我,这是我在这里的第一个问题。
【问题讨论】:
-
字典不能有重复的键。
-
只是为了澄清@Selcuk 提到的内容,因为字典不能有重复的键,当访问您已经访问过的年份值并在上一次迭代中向字典添加值时,它将覆盖关联的当前值那一年用新的
{'Names': '', ...}字典
标签: python list dictionary for-loop duplicates