Skip to content Skip to sidebar Skip to footer

How To Merge Dict Of Dict In Python

Two dictionary is below d1 = {'1': {'index': '1', 'sc': '4', 'st': '3'}, '2': {'index': '2', 'sc': '5', 'st': '5'}} d2 = {'1': {'diff': 1}, '2': {'diff': 0}} Code is below z = {*

Solution 1:

an alternate way using pandas

>>> import pandas as pd
>>> df = pd.DataFrame(d1)
>>> df2 = pd.DataFrame(d2)
>>> merged_dict = pd.concat([df,df2]).to_dict()

output

>>> merged_dict
{'1': {'index': '1', 'sc': '4', 'st': '3', 'diff': 1}, '2': {'index': '2', 'sc': '5', 'st': '5', 'diff': 0}}

Solution 2:

generally, ** will capture any keyword arguments we pass to the function into a dictionary which that attributes arguments will reference. For example:

d1={'a':1,'b':2}
d2={'c':3,'d':4}

def merge(**di):
    res = {}
    for k, v in di.items():
        try:
            res[k].append(v)
        except KeyError:
            res[k] = [v]
    return res

print(merge(**d1, **d2))
# {'a': [1], 'b': [2], 'c': [3], 'd': [4]}

However, if we pass in two dictionary with same keys:

d1 = {'1': {'index': '1', 'sc': '4', 'st': '3'}, '2': {'index': '2', 'sc': '5', 'st': '5'}}
d2 = {'1': {'diff': 1}, '2': {'diff': 0}}

def merge(**di):
    res = {}
    for k, v in di.items():
        try:
            res[k].append(v)
        except KeyError:
            res[k] = [v]
    return res

print(merge(**d1, **d2))
# TypeError: merge() got multiple values for keyword argument '1'

This error is handled by continuing which keep the original one and skip the second dict key. Sorry I don't have a shorthand method for this.

d1 = {'1': {'index': '1', 'sc': '4', 'st': '3'}, '2': {'index': '2', 'sc': '5', 'st': '5'}}
d2 = {'1': {'diff': 1}, '2': {'diff': 0}}

def merge(*args):
    res = {}
    for di in args:
        for k, v in di.items():
            try:
                res[k].update(v)
            except KeyError:
                res[k] = v
    return res

print(merge(d1, d2))
# {'1': {'index': '1', 'sc': '4', 'st': '3', 'diff': 1}, '2': {'index': '2', 'sc': '5', 'st': '5', 'diff': 0}}

Solution 3:

z = {**d2, **d1}

Overwrites everything in d2 with d1 values for keys '1', and '2'. It is tricky to merge dictionaries with the same keys so you don't overwrite key:value pairs within those keys.

The following will get you to the depth needed in both d1 and d2 to update d1 to your expected output:

d1['1']['diff'] = d2['1']['diff']
d1['2']['diff'] = d2['2']['diff']

print ('d1:', d1)

Output:

d1:  {'1': {'index': '1', 'sc': '4', 'st': '3', 'diff': 1}, '2': {'index': '2', 'sc': '5', 'st': '5', 'diff': 0}}

Solution 4:

>>> for key in d1:
...     d1[key].update(d2[key])

>>> d1
{'1': {'index': '1', 'sc': '4', 'st': '3', 'diff': 1}, '2': {'index': '2', 'sc': '5', 'st': '5', 'diff': 0}}

Update:

If you want in another identifier d3.

d3 = d1.copy()
for key in d3:
    d3[key].update(d2[key])

print(d3)

Dictionaries are mutable objects. update function just mutates/updates the object and return None. So, you need to create a copy (so you have another object) and change the new object, if you want initial data unaltered.


Post a Comment for "How To Merge Dict Of Dict In Python"