如果键丢失,我可以在字典列表上使用列表解析吗? [英] Can I use a list comprehension on a list of dictionaries if a key is missing?

查看:164
本文介绍了如果键丢失,我可以在字典列表上使用列表解析吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算具体值出现在字典列表中的次数。但是,我知道这些字典中的一些不具有关键性。我不知道 ,因为这是API调用的结果。

I want to count the number of times specific values appear in a list of dictionaries. However, I know that some of these dictionaries will not have the key. I do not know which though, because these are results from an API call.

例如,这段代码适用于 key1 ,因为所有的字典都有密钥。

As an example, this code works for key1, because all of the dictionaries have the key.

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})

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

However, if I change that last print to:

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

它失败,因为键在两个字典中缺少2

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 的值,如果字典不包含密钥,则不会失败?

How can I use a list comprehension to count the values of key2 and not fail if a dictionary doesn't contain the key?

推荐答案

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

You can explicitly check if key2 is in a dictionary:

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

这篇关于如果键丢失,我可以在字典列表上使用列表解析吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆