1

I have 4 python dictionaries where the value of each key is another dictionary:

a={'a': {'e': 4}}
b={'b': {'f': 5}}
c={'c': {'g': 6}}
d={'d': {'h': 7}}

I want to merge dictionaries a, b, c and d together so that I have one final dictionary that looks like:

{'a': {'e': 4}, 'b': {'f': 5}, 'c': {'g': 6}, 'd': {'h': 7}}

where the order of the parent dictionary is in the order in which I add each original dictionary.

So I created an empty dictionary and did this:

x={} #create empty dictionary
x.update(a) #update with first dictionary
print x
x.update(b) #update with second dictionary
print x
x.update(c) #update with third dictionary
print x
x.update(d) #update with forth dictionary
print x

The result is this:

{'a': {'e': 4}}
{'a': {'e': 4}, 'b': {'f': 5}}
{'a': {'e': 4}, 'c': {'g': 6}, 'b': {'f': 5}}
{'a': {'e': 4}, 'c': {'g': 6}, 'b': {'f': 5}, 'd': {'h': 7}}

I am not sure why, after the third update, that c is added to x between a and b. And then after the forth update, d somehow gets added at the end. It seems random.

Keep in mind, that sorted will not work. The above is an example of what I want and my keys may not always be in alphabetical order. I simple want the order in which I added each dictionary.

Edit: This is for python 2.7, but appreciate answers for 3.6 as I will be migrating a tool from 2 to 3 in the near future.

Mike
  • 4,099
  • 17
  • 61
  • 83

3 Answers3

5

You can just unpack each dict into one (in python3.6+ it will retain order of insertion):

>>> {**a, **b, **c, **c, **d}
{'a': {'e': 4}, 'b': {'f': 5}, 'c': {'g': 6}, 'd': {'h': 7}}

And in python 3.9+ you could use the merge operator:

>>> a | b | c | d
{'a': {'e': 4}, 'b': {'f': 5}, 'c': {'g': 6}, 'd': {'h': 7}}

EDIT

This also works for OrderedDicts. As you are using python 2.7 this will retain order:

>>> from collections import OrderedDict
>>> OrderedDict(**a, **b, **c, **d)
OrderedDict([('a', {'e': 4}), ('b', {'f': 5}), ('c', {'g': 6}), ('d', {'h': 7})])
Jab
  • 26,853
  • 21
  • 75
  • 114
1

"A dictionary is a collection which is unordered, changeable and indexed." - https://www.w3schools.com/python/python_dictionaries.asp, so its only natural that they might not be in the desired order. Use OrderedDict from the collections module if you want your dictionary to keep the order in which keys are inserted.

Bob
  • 236
  • 1
  • 4
1

Dictionaries have no sense of order in Python versions earlier than version 3.6.

Use an OrderedDict if you want to preserve the insertion order:

from collections import OrderedDict

a = {"a": {"e": 4}}
b = {"b": {"f": 5}}
c = {"c": {"g": 6}}
d = {"d": {"h": 7}}

x.update(a)
x.update(b)
x.update(c)
x.update(d)

assert x.keys() == ["a", "b", "c", "d"]
Julia
  • 1,950
  • 1
  • 9
  • 22