Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two dictionaries in python

I'm trying to merge two dictionaries based on key value. However, I'm not able to achieve it. Below is the way I tried solving.

dict1 = {4: [741, 114, 306, 70],
         2: [77, 325, 505, 144],
         3: [937, 339, 612, 100],
         1: [52, 811, 1593, 350]}
dict2 = {1: 'A', 2: 'B', 3: 'C', 4: 'D'}

My resultant dictionary should be

output = {'D': [741, 114, 306, 70],
          'B': [77, 325, 505, 144],
          'C': [937, 339, 612, 100],
          'A': [52, 811, 1593, 350]}

My code

def mergeDictionary(dict_obj1, dict_obj2):
    dict_obj3 = {**dict_obj1, **dict_obj2}
    for key, value in dict_obj3.items():
        if key in dict_obj1 and key in dict_obj2:
               dict_obj3[key] = [value , dict_obj1[key]]
    return dict_obj3

dict_3 = mergeDictionary(dict1, dict2)

But I'm getting this as output

dict_3={4: ['D', [741, 114, 306, 70]], 2: ['B', [77, 325, 505, 144]], 3: ['C', [937, 339, 612, 100]], 1: ['A', [52, 811, 1593, 350]]}
like image 840
Arjun Avatar asked Jan 24 '26 08:01

Arjun


1 Answers

Use a simple dictionary comprehension:

output = {dict2[k]: v for k,v in dict1.items()}

Output:

{'D': [741, 114, 306, 70],
 'B': [77, 325, 505, 144],
 'C': [937, 339, 612, 100],
 'A': [52, 811, 1593, 350]}
like image 92
mozway Avatar answered Jan 26 '26 22:01

mozway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!