合并两个字典列表

合并两个字典列表

本文介绍了合并两个字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[{"APPLE": ["RED"]}, {"BANANA": ["YELLOW", "GREEN"]}, {"APPLE": ["GREEN"]}]

使用此词典列表,我该如何组合相同的键?

Using this list of dictionaries,how can i combine same keys?

[{"APPLE": ["RED","GREEN"]}, {"BANANA": ["YELLOW", "GREEN"]}]

我想得到这个结果.

推荐答案

您可以通过创建用于存储映射的中间字典来以所需的格式实现list(甚至最好使用 collections.defaultdict )为:

You may achieve the list in desired format via creating intermediate dictionary to store the mapping (even better to use collections.defaultdict) as:

from collections import defaultdict

my_list = [{"APPLE": ["RED"]}, {"BANANA": ["YELLOW", "GREEN"]}, {"APPLE": ["GREEN"]}]
temp_dict = defaultdict(list)

for item in my_list:
    for k, v in item.items():
        temp_dict[k] += v

# content of `temp_dict` is:
#     {
#          'APPLE': ['RED', 'GREEN'],
#          'BANANA': ['YELLOW', 'GREEN']
#     }

要将dict转换为所需格式的列表,可以使用 list comprehension 表达式,如下所示:

For converting the dict to the list of desired format, you may use a list comprehension expression as:

>>> new_list = [{k: v} for k, v in temp_dict.items()]
>>> new_list
[{'APPLE': ['RED', 'GREEN']}, {'BANANA': ['YELLOW', 'GREEN']}]

这篇关于合并两个字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:10