Home > Backend Development > Python Tutorial > How Can I Efficiently Merge Nested Dictionaries in Python?

How Can I Efficiently Merge Nested Dictionaries in Python?

Mary-Kate Olsen
Release: 2024-12-03 02:23:10
Original
667 people have browsed it

How Can I Efficiently Merge Nested Dictionaries in Python?

Merging Nested Dictionaries in Python

In Python, we often encounter scenarios where we need to combine multiple nested dictionaries. This task can be challenging, especially when the dictionaries have varying levels of depth and potential conflicts.

To merge dictionaries of dictionaries and maintain the hierarchy, we employ a recursive function:

def merge(a: dict, b: dict, path=[]):
    for key in b:
        if key in a:
            if isinstance(a[key], dict) and isinstance(b[key], dict):
                merge(a[key], b[key], path + [str(key)])
            elif a[key] != b[key]:
                raise Exception('Conflict at ' + '.'.join(path + [str(key)]))
        else:
            a[key] = b[key]
    return a
Copy after login

This function accepts two dictionaries, a and b, along with an optional path parameter for tracking the current path in the merged dictionary. It iterates through each key in b and performs the following actions:

  • If the key exists in a and both values are dictionaries, it recursively merges the two dictionaries and updates the path.
  • If the key exists in a but the values are not dictionaries, it checks for conflicts. If a conflict is detected, an exception is raised.
  • If the key does not exist in a, it adds it to a with the value from b.

Finally, the merged dictionary a is returned.

To merge multiple dictionaries, you can use reduce to combine all dictionaries into a single dictionary:

from functools import reduce
reduce(merge, [dict1, dict2, dict3...])
Copy after login

This operation will add the contents of all dictionaries to the first dictionary in the list.

Example:

dict1 = {1:{'a':{'A'}}, 2:{'b':{'B'}}}
dict2 = {2:{'c':{'C'}}, 3:{'d':{'D'}}}
print(merge(dict1, dict2))

# Output:
# {1:{'a':{'A'}}, 2:{'b':{'B'}, 'c':{'C'}}, 3:{'d':{'D'}}}
Copy after login

Note that the resulting dictionary is stored in dict1.

The above is the detailed content of How Can I Efficiently Merge Nested Dictionaries in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template