如果缺少密钥,我可以在字典列表中使用列表理解吗?

New*_*Guy 3 python counter dictionary list-comprehension

我想计算特定值出现在词典列表中的次数.但是,我知道其中一些词典没有关键.我不知道哪个,因为这些是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)
Run Code Online (Sandbox Code Playgroud)

我得到了一个很好的结果

Counter({'testing': 4, 'prod': 2})
Run Code Online (Sandbox Code Playgroud)

但是,如果我将最后一次打印更改为:

print Counter(r['key2'] for r in list_of_dicts)
Run Code Online (Sandbox Code Playgroud)

它失败了,因为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'
Run Code Online (Sandbox Code Playgroud)

key2如果字典不包含密钥,如何使用列表推导来计算值而不会失败?

ale*_*cxe 8

您可以显式检查是否key2在字典中:

Counter(r['key2'] for r in list_of_dicts if 'key2' in r)
Run Code Online (Sandbox Code Playgroud)