确定两个字典是否相等

确定两个字典是否相等

This question already has answers here:
Comparing two dictionaries and checking how many (key, value) pairs are equal

(26个答案)


2年前关闭。




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

我想要的是:
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

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

最佳答案

==工作

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

希望以上示例对您有所帮助。

09-11 20:23