我想计算特定值出现在词典列表中的次数.但是,我知道其中一些词典没有关键.我不知道哪个,因为这些是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, inprint 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 print Counter(r['key2'] for r in list_of_dicts) KeyError: 'key2'
key2
如果字典不包含密钥,如何使用列表推导来计算值而不会失败?
您可以显式检查是否key2
在字典中:
Counter(r['key2'] for r in list_of_dicts if 'key2' in r)