Python 3.6+: Equality Of Two Dictionaries With Same Keys But In Different Order
Solution 1:
Dictionaries are hash tables, order is not supposed to matter. In python 3.6+ dictionaries are in insertion order but that is just how they are implemented. Order doesn't matter for equality. If you want order to matter in equality use an OrderedDict.
from collections import OrderedDict
d1 = OrderedDict({'foo':123, 'bar':789})
d2 = OrderedDict({'bar':789, 'foo':123})
print(d1 == d2) # False
Solution 2:
Dictionaries were unordered up until Python 3.6. Therefore the only sensible way to test for equality was to ignore the order. When Python 3.6 ordered dictionaries this was an implementation detail. Since Python 3.7 the insertion order can be relied upon. But changing the behavior to only consider dictionaries only equal if the keys are in the same order would break a whole lot of code. And quite frankly I think it is more useful to compare dictionaries without taking the ordering into account.
Post a Comment for "Python 3.6+: Equality Of Two Dictionaries With Same Keys But In Different Order"