Python为每个具有特定键的字典的字典列表创建列表

时间:2016-10-26 23:08:10

标签: python dictionary key

我有一个不一定拥有相同键的字典列表。我正在尝试创建一个包含每个字典中包含特定键的值的新列表。

E.g。

dict1 = {'key1': 1, 'key2': 2, 'key4': 4}
dict2 = {'key2': 2, 'key3': 3}
dict3 = {'key1': 1, 'key2': 2, 'key3': 3}

dict_list = [dict1, dict2, dict3]

现在我正在尝试从dict_list创建一个列表,如下所示:

key2vals = [dict['key2'] for dict in dict_list]
print(key2vals)
   [2, 2, 2]

这很有效,因为'key2'包含在列表中的每个字典中。但是,当我尝试一个没有出现在每个字典中的密钥时,我就会出错。例如。 'KEY1':

>>> key1vals = [dict['key1'] for dict in dict_list]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
KeyError: 'key1'

是否有一种简短明了的方法,我可以做以下的事情,这不起作用?

# This does not work
key1vals = [dict['key1'] if 'key1' in dict for dict in dict_list]

实现这一目标的最恐怖的方法是什么?

解答: for语句和if语句的顺序应该相反:

key1vals = [dict['key1'] for dict in dict_list if 'key1' in dict ]

另外,根据AbrahamB和DJV的建议,我可以在没有搜索键的情况下为这些词典添加默认值:

[dict.get('key1', 0) for dict in dict_list] 

4 个答案:

答案 0 :(得分:2)

绝对。 dict有一个“get”方法,你可以使用它。

例如

a = {}
a.get('this-does-not-exist')

那将返回None类型。

现在你可以变得更加漂亮,例如,如果找不到任何内容,则返回默认值:

a = {}
a.get('this-does-not-exist', [])

将返回一个空列表[]。

答案 1 :(得分:2)

dict1 = {'key1': 1, 'key2': 2, 'key4': 4}
dict2 = {'key2': 2, 'key3': 3}
dict3 = {'key1': 1, 'key2': 2, 'key3': 3}

dict_list = [dict1, dict2, dict3]

keys = ['key1', 'key2', 'key3', 'key4', 'key5']
for key in keys:
    values = [d[key] for d in dict_list if key in d]
    print(values)
[1, 1]
[2, 2, 2]
[3, 3]
[4]
[]

但是,相同的项目查询在此完成两次:key in dd[key]。你可以避免它:

    values = list(filter(None, (d.get(key) for d in dict_list)))

    values = [i for i in (d.get(key) for d in dict_list) if i is not None]

: 正如您在评论中提到的,如果密钥不在dict中,则实际上需要0。只需使用默认值为get的方法:

    values = [d.get(key, 0) for d in dict_list]
[1, 0, 1]
[2, 2, 2]
[0, 3, 3]
[4, 0, 0]
[0, 0, 0]

答案 2 :(得分:1)

你非常接近:

key1vals = [d['key1'] for d in dict_list if 'key1' in d]

获取所有密钥&#39;值:

all_keys = {key for d in dict_list for key in d}

result_dict = {}
for key in all_keys:
    result_dict[key] = [d[key] for d in dict_list if key in d]

print(result_dict)

打印哪些:

{'key1': [1, 1], 'key4': [4], 'key3': [3, 3], 'key2': [2, 2, 2]}

答案 3 :(得分:0)

感谢您的建议!我找到了另一种解决方案,它简单地颠倒了&#34; for&#34;和&#34;如果&#34;我之前尝试的陈述:

>>> key1vals = [dict['key1'] for dict in dict_list if 'key1' in dict]
>>> key1vals
[1, 1]
>>> 

过滤器或&#34;得到&#34;方法比这更受欢迎?