如果缺少键,我可以在字典列表上使用列表理解吗?

Can I use a list comprehension on a list of dictionaries if a key is missing?

我想计算特定值在字典列表中出现的次数。但是,我知道其中一些词典没有密钥。不过,我不知道 哪个 ,因为这些是 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 的值并且不会失败?

您可以明确检查 key2 是否在字典中:

Counter(r['key2'] for r in list_of_dicts if 'key2' in r)
如果密钥不存在,

get 允许您将默认值指定为 return。因此:

In [186]: Counter(r.get('key2',None) for r in list_of_dicts)
Out[186]: Counter({'testing': 3, None: 3})

其中 None 条目告诉我们有多少词典缺少此值。知道这一点可能会很好。如果您不在乎,使用此子句或 if 子句可能并不重要。