【问题标题】:Can I use a list comprehension on a list of dictionaries if a key is missing?如果缺少键,我可以在字典列表上使用列表推导吗?
【发布时间】: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


【解决方案1】:

get 让您指定一个默认值以在密钥不存在时返回。因此:

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

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

【讨论】:

    【解决方案2】:

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

    Counter(r['key2'] for r in list_of_dicts if 'key2' in r)
    

    【讨论】:

      猜你喜欢
      • 2021-05-01
      • 2022-01-13
      • 1970-01-01
      • 2022-06-26
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 2018-07-27
      相关资源
      最近更新 更多