Python3确定两个字典是否相等

时间:2018-11-17 06:52:21

标签: python python-3.x dictionary equality

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

我想要的是:

a = {'foo': 1, 'bar': 2}
b = {'foo': 1, 'bar': 2}
c = {'bar': 2, 'foo': 1}
b = {'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 additioonal elements

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

3 个答案:

答案 0 :(得分:7)

==有效

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

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

答案 1 :(得分:3)

良好的旧==语句有效。

答案 2 :(得分:0)

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}

print(a.items() == b.items())
print(a.items() == c.items())
print(a.items() == d.items())
print(a.items() == e.items())
print(a.items() == f.items())

输出

True
True
False
False
False