김혜지 김혜지 - 4 years ago 157
Python Question

Combine two lists of dictionaries

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


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

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


I want to get this result.

Answer Source

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']
#     }

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']}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download