search

Home  >  Q&A  >  body text

python merge dict

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?

阿神阿神2713 days ago955

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-06-22 11:54:21

    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

    reply
    0
  • 代言

    代言2017-06-22 11:54:21

    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.

    reply
    0
  • Cancelreply