“Python fusionne les dictionnaires imbriqués” Réponses codées

Python fusionne les dictionnaires imbriqués

# 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

fusionner une liste de dictionnaires 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

Réponses similaires à “Python fusionne les dictionnaires imbriqués”

Questions similaires à “Python fusionne les dictionnaires imbriqués”

Plus de réponses similaires à “Python fusionne les dictionnaires imbriqués” dans Python

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code