Home > OS >  Merge two dictionaries in python
Merge two dictionaries in python

Time:11-28

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


Thanks for your help in advance

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

You can do it with pandas:

import pandas as pd

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

enter image description here

CodePudding user response:

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

CodePudding user response:

A dictionary comprehension takes the form {key: value for (key, value) in iterable}

# Python code to demonstrate dictionary
# comprehension

# Lists to represent keys and values
keys = ['a','b','c','d','e']
values = [1,2,3,4,5]

# but this line shows dict comprehension here
myDict = { k:v for (k,v) in zip(keys, values)}

# We can use below too
# myDict = dict(zip(keys, values))

print (myDict)

Output :{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

  • Related