当键乱序时比较字典列表

Comparing list of dictionaries when the keys are out of order

我有 2 个词典列表。

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

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

我敢肯定你不知何故犯了一个错误。我和其他人得到 True:

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

这就是它应该做的。

关于 OrderedDict 的文档说(强调我的):

Equality tests between OrderedDict objects and other Mapping objects are order-insensitive like regular dictionaries.

关于 Value comparisons 的文档是这样说的,这些指令就是这种情况:

Mappings (instances of dict) compare equal if and only if they have equal (key, value) pairs.

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

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