我有一个类似这样的CSV文件:它显示了从1980年到2014年的4个国家的用电量。我正在尝试创建一个嵌套字典,例如
consumption['United States'][1980]
将返回正确的价值。我有一个包含整数列表的数组,我正在尝试创建这样的字典:
file = open('power dataset.csv', 'r')
years = list(range(1980, 2015))
consumption = {}
generation = {}
generation = False
for line in file:
if("Nuclear" in line):
break
split = line.split(",")
if split[0] == "Generation":
generation = True
if "Egypt" == split[0] or split[0] == "Germany" or split[0] == "Netherlands" or split[0] == "United States":
values = split[2:]
if not generation:
i = 0
for year in years:
country = split[0]
consumption[country] = {year: values[i]}
i = i+1
其中values是一个包含相应年份值的数组。我遇到的问题是字典最终只包含一年和一个值(这是最后一个)。因此,如果我尝试打印类似consumption['United States'][1980]
的内容,我会收到错误,因为字典中没有1980年的条目,只有2014年。
我觉得我错过了一些相当简单的东西,但我无法完全理解它。
Here是整个CSV文件。
答案 0 :(得分:3)
问题似乎在于:
for year in years:
consumption[country] = {year: values[i]}
在循环的每次迭代中覆盖consumption[country]
的先前值。
相反,试试这个:
if country in ("Egypt", "Germany", "Netherlands", "United States"):
if not generation:
consumption[country] = {year: vals for year, vals in zip(years, values)}
使用zip
进行字典理解的逐步细分示例:
>>> years = [1980, 1981, 1982, 1983]
>>> values = [1, 2, 3, 4]
>>> zip(years, values)
[(1980, 1), (1981, 2), (1982, 3), (1983, 4)]
>>> {year: vals for year, vals in zip(years, values)}
{1980: 1, 1981: 2, 1982: 3, 1983: 4}
或者,您可以在内部循环之前将consumption[country]
初始化为consumption[country] = {}
,然后在编辑之前使用consumption[country][year] = values[i]
,就像在原始代码中一样。