Skip to main content
 首页 » 编程设计

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

2025年05月04日10bluestorm

我有一个字典列表:

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 循环只需要一次,之后查找速度非常快。