131

This seems trivial, but I cannot find a built-in or simple way to determine if two dictionaries are equal.

What I want is:

a = {'foo': 1, 'bar': 2}
b = {'foo': 1, 'bar': 2}
c = {'bar': 2, 'foo': 1}
d = {'foo': 2, 'bar': 1}
e = {'foo': 1, 'bar': 2, 'baz':3}
f = {'foo': 1}

equal(a, b)   # True 
equal(a, c)   # True  - order does not matter
equal(a, d)   # False - values do not match
equal(a, e)   # False - e has additional elements
equal(a, f)   # False - a has additional elements

I could make a short looping script, but I cannot imagine that mine is such a unique use case.

Bernd Wechner
  • 1,854
  • 1
  • 15
  • 32
Marc Wagner
  • 1,672
  • 2
  • 12
  • 15

2 Answers2

223

== works

a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
a == b == c == d == e
True

I hope the above example helps you.

phoenix
  • 7,988
  • 6
  • 39
  • 45
Sharvin26
  • 2,741
  • 2
  • 9
  • 15
73

The good old == statement works.

Christian Callau
  • 960
  • 6
  • 11
  • 7
    `==` works. For large dictionaries I would however first make a trivial check, which is compare the number of keys. After all there is no need to go deeper into comparing the values if one dictionary has 2 keys but the other 10. – rbaleksandar Nov 17 '18 at 07:08
  • 50
    That's a good way of thinking but it's not necessary. `==` between two dictionaries is very well optimized and takes into account factors like the one you mentioned. – Christian Callau Nov 17 '18 at 07:14
  • 3
    For follow up on @Constantine32 's answer, here's the Cython implementation of dict `==` that does exactly what he says. https://hg.python.org/cpython/file/6f535c725b27/Objects/dictobject.c#l1839 – Scott Driggers Jun 21 '21 at 21:33