Merge two dictionaries in python

Question:

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]]}
Asked By: Arjun

||

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]}
Answered By: mozway

The error seems to be in this line:

dict_obj3[key] = [value , dict_obj1[key]]

You want to use the value as criteria to assign an element to your dictionary, as such:

dict_obj3[value] = dict_obj1[key]

This code should do the trick:

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_obj2.items():
            dict_obj3[value] = dict_obj1[key]
    return dict_obj3

dict_3 = mergeDictionary(dict1, dict2)
print(dict_3)
Answered By: Leno

If you’re using pandas in your project already, it has a method that does precisely what you’re asking for:

import pandas as pd

df1 = pd.DataFrame(dict1)
df1.rename(columns=dict2)
df1

enter image description here

Otherwise it might not be worth the while.

Answered By: Antony Hatchkins

While the simple dictionary comprehension by @mozway is certainly the most straightforward and elegant solution, it rests on the assumption that the keys of dict1 are a subset of those of dict2. If not, you’ll get a KeyError.

If that assumption does not hold, you’ll need to decide for yourself, how you want to deal with the case when a key in dict1 is not present in dict2. One option is to simply discard that key-value-pair and not include it in the output dictionary.

from collections.abc import Mapping

KT = str
VT = list[int]

def merge(
    keys_map: Mapping[int, KT],
    values_map: Mapping[int, VT],
) -> dict[KT, VT]:
    output = {}
    for key, value in values_map.items():
        try:
            output[keys_map[key]] = value
        except KeyError:
            pass
    return output

Test:

if __name__ == "__main__":
    dict1 = {
        5: [1, 2, 3],
        4: [741, 114],
        2: [77, 325],
        3: [937, 339],
        1: [52, 811],
    }
    dict2 = {1: 'A', 2: 'B', 3: 'C', 4: 'D'}
    print(merge(dict2, dict1))

Output:

{'D': [741, 114], 'B': [77, 325], 'C': [937, 339], 'A': [52, 811]}
Answered By: Daniil Fajnberg

You can use dict.update():

def mergeDictionary(dict_obj1, dict_obj2):
    dict_obj3 = dict()
    for key, val in dict_obj1.items():
       dict_obj3.update({dict_obj2[key]: val})
    return dict_obj3

or:

def mergeDictionary(dict_obj1, dict_obj2):
    dict_obj3 = dict()
    for key, val in dict_obj1.items():
       dict_obj3[dict_obj2[key]] = val
    return dict_obj3
Answered By: Arifa Chan
d = {dict2[k]:dict1[k] for k in dict1.keys()}

print(d)
# {'A': [52, 811, 1593, 350], 'B': [77, 325, 505, 144], 'C': [937, 339, 612, 100], 'D': [741, 114, 306, 70]}
Answered By: Laurent B.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.