加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 12:09:53 所属栏目:Python 来源:网络整理
导读:我想计算特定值出现在词典列表中的次数.但是,我知道其中一些词典没有关键.我不知道哪个,因为这些是API调用的结果. 例如,此代码适用于key1,因为所有字典都有密钥. from collections import Counterlist_of_dicts = [ {'key1': 'testing','key2': 'testing'},{
我想计算特定值出现在词典列表中的次数.但是,我知道其中一些词典没有关键.我不知道哪个,因为这些是API调用的结果.

例如,此代码适用于key1,因为所有字典都有密钥.

from collections import Counter
list_of_dicts = [
    {'key1': 'testing','key2': 'testing'},{'key1': 'prod',{'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:Anacondalibcollections.py",line 453,in __init__
    self.update(iterable,**kwds)
  File "h:Anacondalibcollections.py",line 534,in update
    for elem in iterable:
  File "test.py",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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读