I wrote a program and then regretted not making certain objects earlier on OrderedDicts instead of dicts. So to fix this after the fact, the one dictionary was converted into an OrderedDict, but I needed to convert the second dictionary also to become an OrderedDict, but with its keys in the same order as the first.
A dict often displays in a way that looks deceivingly ordered, I almost made a mistake. There's a few questions about this apparent ordering here and here. Anyway, however ordered it may look to the eye, one needs to remember:
{'a':5,'b':7, 'c':3, 'd':9} == {'d':9,'b':7,'a':5, 'c':3}
>> True
So if there are two Python dictionaries:
a = {'a':5, 'b':7, 'c':3, 'd':9}
b = {'c':2, 'b':1, 'd':17, 'a':8}
I can fix the order of a like this:
c = OrderedDict(a)
print (c)
>> OrderedDict([('a', 5), ('b', 7), ('c', 3), ('d', 9)])
How do you impose order on dictionary b, convert it into an OrderedDict with its keys in the same order as a?
In my exact use case, both dictionaries have the same keys, but I would be interested to know how you can do this in general, say instead your two dictionaries were:
a = {'a':5, 'b':7, 'c':3, 'd':9}
b = {'f':3, 'c':2, 'd':17, 'a':8, 'e':9, 'b':1}
How do you convert a and b to OrderedDict's but make sure that whatever keys b has in common with a, they end up in the same order as those keys in a