merge two dictionnary which have list as values in python

To merge two dictionaries with list values in Python, you can use the update() method of the dictionary.

Here is an example:

main.py
dict1 = { 'a': [1,2], 'b': [3,4], 'c': [5,6] }
dict2 = { 'd': [7,8], 'e': [9,10], 'f': [11,12] }

for key in dict2:
    if key in dict1:
        dict1[key].extend(dict2[key])
    else:
        dict1[key] = dict2[key]

print(dict1)
231 chars
11 lines

Output:

main.py
{'a': [1, 2], 'b': [3, 4], 'c': [5, 6], 'd': [7, 8], 'e': [9, 10], 'f': [11, 12]}
82 chars
2 lines

In the above example, we iterate over each key in dict2 and check if it is present in dict1. If it is present, we extend the list in dict1 with the list in dict2 for the corresponding key. If it is not present, we simply add the key-value pair from dict2 to dict1.

gistlibby LogSnag