“Python menggabungkan kamus bersarang” Kode Jawaban

Python menggabungkan kamus bersarang

# Example usage:
# Say you have the following dictionaries and want to merge dict_b into dict_a
dict_a = {"ABC": {"DE": {"F": "G"}}}
dict_b = {"ABC": {"DE": {"H": "I"}, "JKL": "M"}} 

def merge_nested_dictionaries(dict_a, dict_b, path=None):
    """
    recursive function for merging dict_b into dict_a
    """
    if path is None:
        path = []
    for key in dict_b:
        if key in dict_a:
            if isinstance(dict_a[key], dict) and isinstance(dict_b[key], dict):
                merge_nested_dictionaries(dict_a[key], dict_b[key], path + [str(key)])
            # if the b dictionary matches the a dictionary from here on, skip adding it
            elif dict_a[key] == dict_b[key]:
                pass
            # if the same series of keys lead to different terminal values in
            # each dictionary, the dictionaries can't be merged unambiguously
            else:
                raise Exception('Conflict at %s' % '.'.join(path + [str(key)]))
        # if the key isn't in a, add the rest of the b dictionary to a at this point
        else:
            dict_a[key] = dict_b[key]
    return dict_a

# running:
merge_nested_dictionaries(dict_a, dict_b)
# returns:
{'ABC': {'DE': {'F': 'G', 'H': 'I'}, 'JKL': 'M'}}
Charles-Alexandre Roy

Gabungkan daftar kamus Python

>>> from collections import ChainMap
>>> a = [{'a':1},{'b':2},{'c':1},{'d':2}]
>>> dict(ChainMap(*a))
{'b': 2, 'c': 1, 'a': 1, 'd': 2}
Nasty Narwhal

Jawaban yang mirip dengan “Python menggabungkan kamus bersarang”

Pertanyaan yang mirip dengan “Python menggabungkan kamus bersarang”

Lebih banyak jawaban terkait untuk “Python menggabungkan kamus bersarang” di Python

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya