Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 Determine if two dictionaries are equal [duplicate]

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.

like image 889
Marc Wagner Avatar asked Nov 17 '18 06:11

Marc Wagner


People also ask

How do I tell if two dictionaries are identical in Python?

Use == operator to check if the dictionaries are equal You can create the dictionaries with any of the methods defined in Python and then compare them using the == operator. It will return True the dictionaries are equals and False if not.

Can you use == on dictionaries in Python?

According to the python doc, you can indeed use the == operator on dictionaries.


1 Answers

== 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.

like image 104
Sharvin26 Avatar answered Sep 18 '22 00:09

Sharvin26