This is actually quite tricky - particularly if you want a useful error message when things are inconsistent, while correctly accepting duplicate but consistent entries (something no other answer here does..)

Assuming you don't have huge numbers of entries, a recursive function is easiest:

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

# works
print(merge({1:{"a":"A"},2:{"b":"B"}}, {2:{"c":"C"},3:{"d":"D"}}))
# has conflict
merge({1:{"a":"A"},2:{"b":"B"}}, {1:{"a":"A"},2:{"b":"C"}})

note that this mutates a - the contents of b are added to a (which is also returned). If you want to keep a you could call it like merge(dict(a), b).

agf pointed out (below) that you may have more than two dicts, in which case you can use:

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

where everything will be added to dict1.

Note: I edited my initial answer to mutate the first argument; that makes the "reduce" easier to explain

Answer from andrew cooke on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › recursively-merge-dictionaries-in-python
Recursively Merge Dictionaries in Python - GeeksforGeeks
July 23, 2025 - Below, are the methods of Recursively Merge Dictionaries In Python: ... In this example, the code defines a concise `recursive_merge` function to recursively merge dictionaries, handling nested structures. It iterates through the keys of the second dictionary (`dict2`), merging nested dictionaries if present, and updating non-dictionary values.
Discussions

The Idiomatic Way to Merge Dictionaries in Python

Nice read!

Sometimes I'd prefer the "copy and update" just because it can be read easily by novice Python devs. I guess it depends on the project.

That being said, I really like the "Dictionary unpacking" method that I learned from your post!

Thanks!

More on reddit.com
🌐 r/Python
112
328
February 23, 2016
Merge/update nested dictionary
Hi there, I bumped into phyton because I’m looking for some ‘simple code’ to do daily routine calculation and I got stuck. I try to explain what happen with a schematic of the code. Goal to achieve: for each day in a while loop do a calculation with a for cycle which return a dictionary ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
May 16, 2021
dictionary - How to merge two nested dict in python? - Stack Overflow
I have two nested dictionary data. I want to merge them to create one dictionary in python. More on stackoverflow.com
🌐 stackoverflow.com
Nested dictionary. Merging common keys and appending values to list. 0 value isn't appending. Code inside.
Look more closely at your code: for variable in foo[count].keys(): if variable in foo[count].keys(): You're taking each key and then checking if it's one of the keys. Well of course it is. I guess that you didn't mean to do that. (Note also that you don't need the calls to keys() here at all; iterating a dict, and checking membership, work directly on the keys already.) More on reddit.com
🌐 r/learnpython
6
1
November 21, 2021
🌐
GitHub
gist.github.com › angstwad › bf22d1822c38a92ec0a9
Recursive dictionary merge in Python · GitHub
Here's a Python 3 version with a test case that: a) returns a new dictionary rather than updating the old ones, and b) controls whether to add in keys from merge_dct which are not in dct. from unittest import TestCase import collections def dict_merge(dct, merge_dct, add_keys=True): """ Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys.
🌐
Reddit
reddit.com › r/python › the idiomatic way to merge dictionaries in python
r/Python on Reddit: The Idiomatic Way to Merge Dictionaries in Python
February 23, 2016 - If you have deep/nested data structures that you want to merge deeply (e.g., when keys collide and they are both lists, merge the lists instead of clobbering,) you're basically stuck with creating a function that checks for those cases and handles them appropriately. ... Nice article, very accurate. I love the unpacking approach. In practice I'm on Python 3.4 and usually use the copy and update approach.
🌐
SitePoint
sitepoint.com › python hub › nested dictionaries
Python - Nested Dictionaries | SitePoint — SitePoint
The deep_merge function takes two dictionaries, dict1 and dict2, and merges then. It handles merging nested dictionaries recursively.
🌐
Readthedocs
deepmerge.readthedocs.io
Deepmerge: merging nested data structures — deepmerge 0.1 documentation
[ (list, ["append"]), (dict, ["merge"]), (set, ["union"]) ], # next, choose the fallback strategies, # applied to all other types: ["override"], # finally, choose the strategies in # the case where the types conflict: ["override"] ) base = {"foo": ["bar"]} next = {"bar": "baz"} my_merger.merge(base, next) assert base == {"foo": ["bar"], "bar": "baz"}
🌐
freeCodeCamp
forum.freecodecamp.org › python
Merge/update nested dictionary - Python - The freeCodeCamp Forum
May 16, 2021 - Hi there, I bumped into phyton because I’m looking for some ‘simple code’ to do daily routine calculation and I got stuck. I try to explain what happen with a schematic of the code. Goal to achieve: for each day in a while loop do a calculation with a for cycle which return a dictionary d_for_calc before update while loop counter update a dictionary d_while_calc{date:d_for_calc} something like: d_for_calc{} d_while_calc{} data=begin_date while date
Find elsewhere
🌐
PyPI
pypi.org › project › deepmerge
deepmerge · PyPI
[ (list, ["append"]), (dict, ["merge"]), (set, ["union"]) ], # next, choose the fallback strategies, # applied to all other types: ["override"], # finally, choose the strategies in # the case where the types conflict: ["override"] ) base = {"foo": ["bar"]} next = {"bar": "baz"} my_merger.merge(base, next) assert base == {"foo": ["bar"], "bar": "baz"}
      » pip install deepmerge
    
Published   Aug 30, 2024
Version   2.0
🌐
Trey Hunner
treyhunner.com › 2016 › 02 › how-to-merge-dictionaries-in-python
How to Merge Dictionaries in Python
Should there be an updated built-in instead (kind of like sorted)? ... Accurate: no. This doesn’t work. Idiomatic: no. This doesn’t work. Since Python 3.5 (thanks to PEP 448) you can merge dictionaries with the ** operator:
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-merging-two-dictionaries
Merging or Concatenating Two Dictionaries in Python - GeeksforGeeks
| operator introduced in Python 3.9 can be used to merge dictionaries.
Published   November 1, 2025
🌐
freeCodeCamp
freecodecamp.org › news › python-merge-dictionaries-merging-two-dicts-in-python
Python Merge Dictionaries – Merging Two Dicts in Python
May 11, 2023 - { 'name': 'Ihechikara', 'age': ... } You can use the double asterisk (also called double star) operator (**) to "unpack" and merge the key and value pairs of two or more dictionaries into a variable....
🌐
Stack Abuse
stackabuse.com › how-to-merge-two-dictionaries-in-python
How to Merge Two Dictionaries in Python
August 31, 2023 - From Python version 3.9 onward, we can use the merge operators (represented by | ) to combine two dictionaries: >>> x = a | b >>> print(x) {1: 'fish', 2: 'chips', 3: 'jelly', 4: 'time'} The dictionary merge operators can also be used in the place of nested dictionaries too.
Top answer
1 of 7
10

This code is to support slightly different meaning of "merge". Let's say we have a nested dictionary:

dict1 = {'employee':{'devs':{'python':{'dev1':'Roy'}}}}
dict2 = {'employee':{'devs':{'cpp':{'dev1':'Biswas'}}}}

In this case the simple loop solution returns:

{'employee': {'devs': {'cpp': {'dev1': 'Biswas'}}}}

While the "intuitive" answer should be:

{'employee': {'devs': {'python': {'dev1': 'Roy'}, 'cpp': {'dev1': 'Biswas'}}}}

This is just a simple example, the real example may be much more complex.

Below is my attempt for such a nested dictionary. It works for nested data using recursion. And it also has some restrictions. For example if dict1 and dict2 have the same value which is not dictionary, dict2 has priority. On the other hand if dict1 contains dictionary and dict2 contains value with the same key, the priority is upon dict1 and dict2 is ignored. Other restrictions will require code changes.

def merge_dict(dict1, dict2):
    for key, val in dict1.items():
        if type(val) == dict:
            if key in dict2 and type(dict2[key] == dict):
                merge_dict(dict1[key], dict2[key])
        else:
            if key in dict2:
                dict1[key] = dict2[key]

    for key, val in dict2.items():
        if not key in dict1:
            dict1[key] = val

    return dict1

dict1 = merge_dict(dict1, dict2)
2 of 7
8

You can just update the inner dictionary.

>>> dict1 = {'employee':{'dev1': 'Roy'}}
>>> dict2 = {'employee':{'dev2': 'Biswas'}}
>>> 
>>> for key in dict1:
...     if key in dict2:
...         dict1[key].update(dict2[key])
... 
>>> dict1
{'employee': {'dev2': 'Biswas', 'dev1': 'Roy'}}
🌐
Learn By Example
learnbyexample.org › python-nested-dictionary
Python Nested Dictionary - Learn By Example
June 20, 2024 - In this example, the deep_update function iterates through the keys and values of the second dictionary. If a value is itself a dictionary (a collections.abc.Mapping), the function recursively calls itself to merge the nested dictionaries. Otherwise, it simply updates the value in the source dictionary.
🌐
Reddit
reddit.com › r/learnpython › nested dictionary. merging common keys and appending values to list. 0 value isn't appending. code inside.
r/learnpython on Reddit: Nested dictionary. Merging common keys and appending values to list. 0 value isn't appending. Code inside.
November 21, 2021 -

Code: https://pastebin.com/GJn74YX5

I have a nested dictionary with the data structure:

foo[count] [string variable] = value

foo = { 0 : { "a": 2,	"b": 5,	"c": 6},
        1 : { "a": 3,	"b": 8,	"d": 9},
        2 : { "b": 5,	"d": 9,	"c": 3}}

I want to take common values of these dicts and combine common values to the appropriate key variable. Perhaps doable in a new dict. If the common variable is not available for that specific count, it will add a 0. All values should be the same length in the new dict. To to look like this:

{ "a": [2, 3, 0], "b": [5, 8, 5], "c":[6, 0, 3], "d": [0,9,9] }

My approach:

  1. Create newdict a defaultdict(list) so i can check if key exists and append to the list like seen above. This will be the final dict I want

     newdict = defaultdict(list)  
  2. Create the following for loop to append to the new dict:

    for count in foo.keys():
        for variable in foo[count].keys():
            if variable in foo[count].keys():
                newdict[variable].append(foo[count].get(variable))
            elif variable not in foo[count].keys():
                newdict[variable].append(0)		
            else:
                newdict[variable] = foo[count].get(variable)

My problem:

Output:

{ "a": [2, 3], "b": [5, 8, 5], "c":[6, 3], "d": [9,9] }
  • The newdict seem to merge all the values but it seems to always go toward the first if statement

  • The elif block is never reached -- 0 is never appended to the list

  • The else block is also never reached but it seems to be appending right so might not be a big deal(?)

I spent hours and cant seem to wrap my ahead why 0 isn't appending. Any help is appreciated. Thank you in advance!

🌐
Better Programming
betterprogramming.pub › how-to-merge-two-dictionaries-in-a-single-expression-f1f9f2f9787e
How to Merge Two Dictionaries in a Single Expression in Python | by Jonathan Hsu | Better Programming
October 14, 2019 - def merge_dictionaries(first_dict, second_dict): merged = first_dict.copy() merged.update(second_dict) return mergedd1 = { "A": "Auron", "B": "Braska", "C": "Crusaders" } d2 = { "C": "Cid", "D": "Dona" }print(merge_dictionaries(d1,d2)) # {'A': 'Auron', 'B': 'Braska', 'C': 'Cid', 'D': 'Dona'} Starting in Python 3.5, the the double asterisk can be used to unpack a dictionary.
🌐
Quora
quora.com › How-do-I-merge-multiple-dictionaries-values-having-the-same-keys-in-Python-but-different-lengths
How to merge multiple dictionaries values having the same keys in Python but different lengths - Quora
Python (programming langu... ... Dictionaries (programming... ... Keys don't need to be of same length. But they are still different as there can't be duplicate keys. Merging dictionaries is a matter of deciding what to do with the Values when a key exists in both.
🌐
FavTutor
favtutor.com › blogs › merge-dictionaries-python
Python Merge Dictionaries (8 Ways to Merge Two Dicts)
November 28, 2023 - Below are the 8 unique methods by which you can concatenate two dictionaries in python: You can merge two dictionaries in python using the update() method. Using the update method, the first dictionary is merged with the other one by overwriting it.
🌐
Medium
medium.com › @ryan_forrester_ › python-nested-dictionaries-complete-guide-8a61b88a2e02
Python Nested Dictionaries: Complete Guide | by ryan | Medium
October 24, 2024 - Here’s a function to merge nested dictionaries, useful for combining configuration files: