gpt4 book ai didi

python - 循环中的嵌套字典

转载 作者:太空宇宙 更新时间:2023-11-04 00:39:21 25 4
gpt4 key购买 nike

我有一个看起来像这样的 CSV 文件:enter image description here它显示了 4 个国家从 1980 年到 2014 年的用电量。我正在尝试创建一个嵌套字典,例如 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 文件。

最佳答案

问题似乎在于:

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] 与编辑前的原始代码相同。

关于python - 循环中的嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42560364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com