“python mesclar dicionários aninhados” Respostas de código

python mesclar dicionários aninhados

# 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

mesclar uma lista de dicionários 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

Respostas semelhantes a “python mesclar dicionários aninhados”

Perguntas semelhantes a “python mesclar dicionários aninhados”

Mais respostas relacionadas para “python mesclar dicionários aninhados” em Python

Procure respostas de código populares por idioma

Procurar outros idiomas de código