Python3 判断两个字典是否相等

标签 python python-3.x dictionary equality

<分区>

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

我想要的是:

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

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

关于Python3 判断两个字典是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53348959/

相关文章:

python - 国际象棋程序OO设计

python-3.x - 使用 ctypes 获取可用工作区

python - 解析作为 POST 参数传递的字典列表

javascript - 如何根据显示的记录更改图像和 JS?

python - 如何在文本文件中搜索单词并使用 Python 打印部分行?

python - 有没有更简单的方法来转换这些 python 对象

python - 嵌套生成器表达式的行为异常

python - 系列的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

python - Pandas - 根据 A 列中的值访问 B 列中的值

python-3.x - 简单的语法在 Python 中给出 ValueError