gpt4 book ai didi

python - 在遍历字典列表时避免 KeyError

转载 作者:太空宇宙 更新时间:2023-11-04 07:16:24 26 4
gpt4 key购买 nike

我有一个字典列表:

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'

我知道我可能犯了一个愚蠢的错误,但有什么帮助吗?

最佳答案

列表理解 + if

如果你想要所有的值,你需要先检查字典是否有对应的键:

>>> [d['first'] for d in test if 'first' in d]
['1', '0']
>>> [d['sixth'] for d in test if 'sixth' in d]
[]

只有一个值

您可以使用 next 来获取与第一次出现的 'first' 相对应的值,如果您确定它们至少是一个带有 'first' 值:

>>> test = [{'first': '1'}, {'second': '2'}, {'first': '0'}, {'third': '3'}, {'fourth': '4'}]
>>> next(d['first'] for d in test if 'first' in d)
'1'

它引发一个 StopIteration 否则:

>>> next(d['sixth'] for d in test if 'sixth' in d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

替代数据格式

最后,如果您经常执行此操作,稍微更改一下格式可能会很有趣:

from collections import defaultdict
data = defaultdict(list)

test = [{'first': '1'}, {'second': '2'}, {'first': '0'}, {'third': '3'}, {'fourth': '4'}]

for d in test:
for k in d:
data[k].append(d[k])

print(data)
# defaultdict(<type 'list'>, {'second': ['2'], 'fourth': ['4'], 'third': ['3'], 'first': ['1', '0']})
print(data['first'])
# ['1', '0']
print(data['sixth'])
# []

for 循环只需要一次,之后查找速度非常快。

关于python - 在遍历字典列表时避免 KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44070131/

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