检查Python中未排序字典列表的相等性

问题描述 投票:0回答:2

我想检查两个未排序的字典列表是否具有相同的内容,即使顺序可能不同。

in
检查还不够好,因为可能存在重复的字典。 (例如
list1 = [dict1, dict1, dict2]
list2 = [dict1, dict2, dict2]

如果是列表列表,我只会对它们进行排序:

sorted(list_of_lists1) == sorted(list_of_lists2)

但是字典排序不稳定。

我可以通过将所有字典转换为元组来解决这个问题,但这似乎效率低下且蹩脚。

有更直接的解决办法吗?

python dictionary
2个回答
7
投票

我认为您不需要散列任何内容 - 您可以将每个字典更改为键值对元组的排序列表,然后对其进行排序。

def dict_list_eq(l1, l2):
    sorted_l1 = sorted(sorted(d.items()) for d in l1)
    sorted_l2 = sorted(sorted(d.items()) for d in l2)
    return sorted_l1 == sorted_l2

l1 = [{1: 2}, {3: 4}]
l2 = [{3: 4}, {1: 2}]
l3 = [{1: 209}, {3: 4}]

print(dict_list_eq(l1, l2))
print(dict_list_eq(l1, l3))

输出,如预期:

True
False

0
投票

如果您希望确保每个列表中完全相同的对象出现相同的次数,您可以依赖 id (https://docs.python.org/3/library/functions.html#id )的字典,并进行您提到的排序:

if sorted(id(d) for d in list1) == sorted(id(d) for d in list2):
    ...

如果您正在寻找可能相等但不是同一个 python 对象的字典,那么这将不起作用。

© www.soinside.com 2019 - 2024. All rights reserved.