python - 当键乱序时比较字典列表

标签 python python-3.x list dictionary equality

我有 2 个字典列表。

a = [{"name": "hello", "city": "xyz"},{"city": "rty", "name": "ert"}]
b = [{"city": "xyz","name": "hello"},{"name": "ert", "city": "rty"}]

上面两个列表是相等的。但如果我使用 == 进行比较,它会给出 False。当键可能乱序时,如何检查两个字典列表之间的相等性?

最佳答案

如果您想知道每个列表是否具有相同的字典,即使字典元素可能不在列表中的相同位置(正如您在注释中提到的那样),您可以使用:

a = [{"name": "hello", "city": "xyz"},{"city": "rty", "name": "ert"}]
b = [{"name": "ert", "city": "rty"}, {"city": "xyz","name": "hello"}]

print(a == b)
print(sorted(a, key=lambda d: sorted(d.items())) == sorted(b, key=lambda d: sorted(d.items())))

输出:

False
True

关于python - 当键乱序时比较字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60682655/

相关文章:

python - 为什么 Python 不索引我的列表并用新的索引版本覆盖它?仍在打印原件

C - List在所有节点中递归保存数据

python通过模拟测试装饰装饰器

python-3.x - 如何将检查指定可执行文件是否正在运行的子进程函数更改为同时适用于 Python 2 和 3?

Python 在迭代过程中就地修改字典条目

python - 如果你从另一个脚本中导入一个装饰过的 python 函数会发生什么?

python - df.loc 导致 SettingWithCopyWarning 警告消息

python - 为什么我无法在 python 中使用 youtube-dl 下载 mp4 文件

python - 在嵌套的有序字典 python 中查找给定键的值

python - 为什么 list() 与一个对象分别显示不同的结果?