这段看似简单的代码给了我一个关键错误。我做错了什么?
a = [{"a": [1,2,3]}, {"b": [1,2,3]}, {"c": [1,2,3]}]
b = [dict["a"] for dict in a]
print(b)
Traceback (most recent call last):
File "G:/mydir/myscript.py", line 2, in <module>
b = [dict["a"] for dict in a]
File "G:/mydir/myscript.py", line 2, in <listcomp>
b = [dict["a"] for dict in a]
KeyError: 'a'
在a
的三个字典中,只有第一个字典包含键"a"
。您可以使用.get(<key>)
方法,如果键不在字典中,它将返回None
。
例如
a = [{"a": [1,2,3]}, {"b": [1,2,3]}, {"c": [1,2,3]}]
b = [dict.get("a") for dict in a]
print(b) # output: [[1,2,3], None, None]
我还建议不要使用名称dict
,因为Python使用它与字典类交互,所以也许您可以考虑将其更改为类似
a = [{"a": [1,2,3]}, {"b": [1,2,3]}, {"c": [1,2,3]}]
b = [d.get("a") for d in a]
print(b) # output: [[1,2,3], None, None]
如果你想让你的代码按照你设置问题的方式工作,你需要确保a
中的每个字典都有"a"
键,即像
a = [{"a": [1,2,3]}, {"a": [1,2,3]}, {"a": [1,2,3]}]