简体   繁体   中英

How to merge two dictionaries based on their keys and values in Python?

I have a problem with merging two dictionaries in Python based on its keys and values. I have the following case:

dictionary_1 = { 1{House: red, index=1} , 2{House: blue, index=2} , 3{House: green, index=3}}



dictionary_2 = { 4{Height: 3, index =3} , 5{Height: 5, index=1} , 6{Height: 6, index=2}

So for example in "dictionary_1" , i have the big dictionary whose keys are "1" and "2" and "3" , and its values are "{House: red, index=1}" and "{House: blue, index=2}" and "{House: green, index=3}". As you can see the values of the big dictionary are also dictionaries themself. The same logic applies also for the dictionary_2.

My goal is to compare the values of the two big dictionaries: "dictionary_1" and "dictionary_2". Then, if the "Index" items of two dictionaries have the same values, I want to merge them together, without duplicating the "index" item.

Therefore the output should be something like:

dictionary_output = { 1{House: red, index=1, Height:5} , 2{House: blue, index=2, Height:6} , 3{House: green, index=3, Height: 3}}

setdefault is your friend in problems like this

dictionary_1 = { 1: { "House": "red", "index": 1},
                 2: { "House": "blue", "index": 2},
                 3: { "House": "green", "index": 3}}

dictionary_2 = { 4: { "Height": 3, "index": 3},
                 5: { "Height": 5, "index": 1},
                 6: { "Height": 6, "index": 6}}

output = {}

for k, v in dictionary_1.items():
    o = output.setdefault(v.get("index"), {})
    o['House'] = v['House']
    o['index'] = v['index']

for k, v in dictionary_2.items():
    o = output.setdefault(v.get("index"), {})
    o['Height'] = v['Height']
print(output)

will yield:

{1: {'House': 'red', 'Height': 5, 'index': 1}, 2: {'House': 'blue', 'index': 2}, 3: {'House': 'green', 'Height': 3, 'index': 3}, 6: {'Height': 6}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM