【发布时间】:2016-04-15 02:45:20
【问题描述】:
我想计算特定值出现在字典列表中的次数。但是,我知道其中一些字典不会有密钥。我不知道哪个,因为这些是 API 调用的结果。
例如,此代码适用于 key1,因为所有字典都有密钥。
from collections import Counter
list_of_dicts = [
{'key1': 'testing', 'key2': 'testing'},
{'key1': 'prod', 'key2': 'testing'},
{'key1': 'testing',},
{'key1': 'prod',},
{'key1': 'testing', 'key2': 'testing'},
{'key1': 'testing',},
]
print Counter(r['key1'] for r in list_of_dicts)
我得到了很好的结果
Counter({'testing': 4, 'prod': 2})
但是,如果我将最后的打印更改为:
print Counter(r['key2'] for r in list_of_dicts)
它失败了,因为key2 在一些字典中丢失了。
Traceback (most recent call last):
File "test.py", line 11, in <module>
print Counter(r['key2'] for r in list_of_dicts)
File "h:\Anaconda\lib\collections.py", line 453, in __init__
self.update(iterable, **kwds)
File "h:\Anaconda\lib\collections.py", line 534, in update
for elem in iterable:
File "test.py", line 11, in <genexpr>
print Counter(r['key2'] for r in list_of_dicts)
KeyError: 'key2'
如何使用列表推导来计算 key2 的值,并且在字典不包含键的情况下不会失败?
【问题讨论】:
-
key不存在怎么办?
标签: python dictionary counter list-comprehension