0

I want to merge two dictionaries but the order doesn't need to change. Dictionary 2 needs to be "pasted" behind Dictionary 1. (or vice versa)

d1 = {'a': 100, 'b': 200}
d2 = {'x': 300, 'y': 200}
d3 = ?
print d3
>>> {'x': 300, 'y': 200, 'a': 100, 'b': 200}

I tried using the python3 way of combining dictionaries:

d1 = {'a': 100, 'b': 200}
d2 = {'x': 300, 'y': 200}
d3 = {**d1, **d2}
print(d3)
>>> {'y': 200, 'b': 200, 'a': 100, 'x': 300}

But the order is not remained. Any help?

Jesse
  • 175
  • 1
  • 1
  • 8
  • 1
    Briefly: the order doesn't remain because it was never there in the first place. Dictionaries are arbitrarily ordered. If order matters, you will need to use a different class, like `OrderedDict`, as shown in the linked question's answers. – TigerhawkT3 Sep 10 '16 at 11:19
  • Wait a while for Python 3.6; Python 3.6 **will retain the ordering of dictionary**. – Antti Haapala -- Слава Україні Sep 10 '16 at 11:20
  • @AnttiHaapala - I'm not sure whether that will be enough to replace `OrderedDict`, as [the changelist](https://docs.python.org/3.6/whatsnew/3.6.html) says that it's specifically for maintaining the order of `**kwargs` (i.e., for the `dict()` constructor), so it might not apply to literals. It also says that this is currently an implementation detail that shouldn't be relied upon. – TigerhawkT3 Sep 10 '16 at 11:28
  • @TigerhawkT3 I've tested it, it applies to every single dictionary, including updates and so on. Yes, it is currently an implementation detail though. But it also works for this one. – Antti Haapala -- Слава Україні Sep 10 '16 at 11:29
  • @TigerhawkT3: insertion order is maintained. Literals are processed from left to right, so `{'a': 1: 'b': 2}` places `'a'` first. There is a long-standing bug that in dictionaries displays, the value expression is evaluated before the key expression, but key-value pairs retain their order in 3.6. – Martijn Pieters Sep 10 '16 at 11:32
  • @AnttiHaapala and Martijn - thanks, I will keep that in mind. – TigerhawkT3 Sep 10 '16 at 11:36

0 Answers0