字典列表在 Python 中引发了一个关键错误

M D*_*M D 1 python dictionary list keyerror

我有一个字典列表,我想分别计算“增加”和“减少”键的值。我的脚本返回了一个关键错误,这可能是因为并非所有词典都有“增加”和“减少”。但我不知道如何解决它。作为 Python 初学者,任何帮助将不胜感激。

list_of_dicts = [{"decreasing": 1}, {"increasing": 4}, {"decreasing": 1}, {"increasing": 3},{"decreasing": 1},
             {"increasing": 1}]

values1 = [a_dict["decreasing"] for a_dict in list_of_dicts]
values2 = [a_dict["increasing"] for a_dict in list_of_dicts]

print(values1)
print(values2)
Run Code Online (Sandbox Code Playgroud)

预期的结果是:

[1,1,1]
[4,3,1]
Run Code Online (Sandbox Code Playgroud)

And*_*ely 5

您可以使用sum()+dict.get和默认值0

values1 = sum(d.get("increasing", 0) for d in list_of_dicts)
values2 = sum(d.get("decreasing", 0) for d in list_of_dicts)

print("Increasing:", values1)
print("Decreasing:", values2)
Run Code Online (Sandbox Code Playgroud)

印刷:

Increasing: 29
Decreasing: 9
Run Code Online (Sandbox Code Playgroud)

编辑:获取值:


values1, values2 = [], []
for d in list_of_dicts:
    if "increasing" in d:
        values1.append(d["increasing"])
    elif "decreasing" in d:
        values2.append(d["decreasing"])

print("Increasing:", values1)
print("Decreasing:", values2)
Run Code Online (Sandbox Code Playgroud)

印刷:

Increasing: [4, 3, 1, 5, 11, 1, 4]
Decreasing: [1, 1, 1, 1, 2, 1, 2]
Run Code Online (Sandbox Code Playgroud)