Python Forum

Full Version: dictionary insertion order
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
if two dictionaries have exactly the same key and value pairs but also have a different insertion order as shown by this little test code:
dx = {}
dx['a'] = 1
dx['b'] = 2
dx['c'] = 3
dy = {}
dy['c'] = 3
dy['b'] = 2
dy['a'] = 1
print(dx==dy)
the result is True when run on my CPython 3.8.10.

is this (ignoring insertion order when comparing dictionaries) guaranteed to be so for all compliant interpreters?

what is the appropriate way to compare the insertion order of two dictionaries?

what is the appropriate way to compare the insertion order of two dictionaries even if their values are different (even though the keys are the same with the insertion order being either the same or different)?
If you also want to compare with insertion order, then use an OrderedDict.

from collections import OrderedDict

dx = {}
dx["a"] = 1
dx["b"] = 2
dx["c"] = 3

dy = {}
dy["c"] = 3
dy["b"] = 2
dy["a"] = 1

# The order is not checked
print("Dict equalness:", dx == dy)

# If you want include the order for comparison
# then use a OrderedDict
odx = OrderedDict(dx)
ody = OrderedDict(dy)

print("OrderedDict equalness:", odx == ody)

# and if you have an OrderedDict, but do not want to
# check the insertion order for equalness
print("OrderedDict -> dict equalness:", dict(odx) == dict(ody))


# or inline it
odx2 = OrderedDict({"a": 1, "b": 2, "c": 3})
ody2 = OrderedDict({"c": 3, "b": 2, "a": 1})
You could also check, if both dicts do have the same keys, without checking the values.

dx2 = {"a": 1, "b": 2, "c": 3}
dy2 = {"c": 30, "b": 20, "a": 10}

same_keys = not (dx2.keys() ^ dy2.keys())

if same_keys:
    print("dx2 and dy2 have the same keys")
    print("Values were not compared.")
The ordered dict does not return a set, if the key() method were called.
Instead, a list is returned. So you can check if the keys are the same and if they are in the same order.

dx3 = {"a": 1, "b": 2, "c": 3}
dy3 = {"c": 30, "b": 20, "a": 10}

odx3 = OrderedDict(dx3)
ody3 = OrderedDict(dy3)

same_keys = odx3.keys() == ody3.keys()

if same_keys:
    print("odx3 and ody3 have the same keys in the same order.")
    print("Values were not compared.")
oooh, i didn't think about comparing .keys() to compare the insertion order. but that seems to work.
dx = {}
dx['a'] = 1
dx['b'] = 2
dx['c'] = 3
dy = {}
dy['c'] = 3
dy['b'] = 2
dy['a'] = 1
print(dx==dy)
print(dx.keys())
print(dy.keys())