Python3 判断两个字典是否相等

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53348959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:17:01  来源:igfitidea点击:

Python3 Determine if two dictionaries are equal

pythonpython-3.xdictionaryequality

提问by Marc Wagner

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.

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

回答by Sharvin26

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

我希望上面的例子对你有帮助。

回答by Constantine32

The good old ==statement works.

好的旧==语句有效。

回答by Srce Cde

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())

Output

输出

True
True
False
False
False