Aug-09-2023, 07:29 PM
If you also want to compare with insertion order, then use an
Instead, a
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.")
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!