Python 3确定两个字典是否相等

这看起来微不足道,但我找不到一种内置的或简单的方法来确定两个字典是否相等。

我想要的是:

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

我可以编写一个简短的循环脚本,但是我无法想象我的脚本是如此独特的用例。

138784 次浏览

The good old == statement works.

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