【发布时间】:2017-10-19 14:07:56
【问题描述】:
我有一个字典列表:
test = [{'first': '1'}, {'second': '2'}, {'first': '0'}, {'third': '3'}, {'fourth': '4'}]
但是当我这样做时:
stuff = [L['first'] for L in test]
print(stuff)
我明白了:
Traceback (most recent call last):
File "C:/Users/User/Desktop/test_run.py", line 4, in <module>
stuff = [L['first'] for L in test]
File "C:/Users/User/Desktop/test_run.py", line 4, in <listcomp>
stuff = [L['first'] for L in test]
KeyError: 'first'
我知道我可能犯了一个愚蠢的错误,但有什么帮助吗?
【问题讨论】:
-
在您的列表中,并非所有字典都以
first为键 -
但在我只想要“第一”的东西中,我需要为此设置一个 if 条件吗?
-
没有
TypeError -
你期望结果是什么?
-
@Paul,是的。这样做 -
stuff = [L['first'] for L in test if L.get('first')]
标签: python dictionary list-comprehension