python merge dict
阿神
阿神 2017-06-22 11:52:21
0
2
959

Now there are two dicts. This dict has two levels (it would be better if the number of levels can be customized or unlimited) and I want to merge them

case1:
Input: a: {1:{"171": True}} b:{1:{"172": False}}
Output: {1:{"171": True , "172": False}}

case2:
Input: a: {1:{"171": True}} b:{1:{"171": False}}
Output: {1:{"171": False }}

The dict.update method I use in python can only be used in one layer. Is there any good implementation method?

阿神
阿神

闭关修行中......

reply all(2)
洪涛

I just wrote a merge that handles multi-layer dictionaries

from itertools import chain
from functools import reduce


def deep_merge_func(acc, item):
    if not acc:
        acc = {}
    k, v = item
    if isinstance(v, dict):
        original_v = acc.get(k)
        if original_v and isinstance(original_v, dict):
            return {**acc, k: deep_merge(original_v, v)}
    return {**acc, k: v}



def deep_merge(origin, target):
    return reduce(deep_merge_func, chain(origin.items(), target.items()), None)


a = {1: {"171": True}}
b = {1: {"171": False}}

print(deep_merge(a, b))


c = {1: {"171": True}}
d = {1: {"172": False}}
print(deep_merge(c ,d))

Only tested python3.6.1, you only need to call deep_merge

The writing is more functional, don’t blame me

代言

For case2 it is relatively simple:

>>> a={1:{"171": True}}
>>> b={1:{"171":False}}
>>> a.update(b)
>>> a
{1: {'171': False}}

For case1 you can do this:

>>> c={}
>>> for k,v in a.items():
...     if k in b:
...         v.update(b[k])
...         c[k] = v
... 
>>> c
{1: {'172': False, '171': True}}

You can encapsulate the above operations into functions.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template