我正在尝试找到一种方法来对 Python 3.6 中的两个字典列表进行排序和比较。我最终只希望 list_dict_a
和 list_dict_b
与 ==
进行比较并评估为 True
。
这是数据的样子:
list_dict_a = [
{'expiration_date': None, 'identifier_country': None, 'identifier_number': 'Male', 'identifier_type': 'Gender', 'issue_date': None},
{'expiration_date': None, 'identifier_country': 'VE', 'identifier_number': '1234567', 'identifier_type': 'Foo No.', 'issue_date': None}]
list_dict_b = [
{'identifier_country': 'VE', 'expiration_date': None, 'identifier_type': 'Foo No.', 'issue_date': None, 'identifier_number': '1234567'},
{'identifier_country': None, 'expiration_date': None, 'identifier_type': 'Gender', 'issue_date': None, 'identifier_number': 'Male'}]
数据相同,但顺序不同(我无法控制初始顺序)。
当我尝试这样比较它们时,我在做这样的事情时得到了一个错误的值:
print("这是否匹配任何内容",list_dict_a == list_dict_b)
这甚至可以做到吗?
最佳答案
您可以在比较它们之前对两个列表进行排序,并比较排序后的结果:
>>> list_dict_a = [
{'expiration_date': None, 'identifier_country': None, 'identifier_number': 'Male', 'identifier_type': 'Gender', 'issue_date': None},
{'expiration_date': None, 'identifier_country': 'VE', 'identifier_number': '1234567', 'identifier_type': 'Foo No.', 'issue_date': None}]
>>> list_dict_b = [
{'identifier_country': 'VE', 'expiration_date': None, 'identifier_type': 'Foo No.', 'issue_date': None, 'identifier_number': '1234567'},
{'identifier_country': None, 'expiration_date': None, 'identifier_type': 'Gender', 'issue_date': None, 'identifier_number': 'Male'}]
>>> list_dict_a == list_dict_b
False
>>> def key_func(d):
items = ((k, v if v is not None else '') for k, v in d.items())
return sorted(items)
>>> sorted(list_dict_a, key=key_func) == sorted(list_dict_b, key=key_func)
True
每个列表中的字典顺序将无关紧要。
需要传递 key
函数,因为字典是不可排序的,因此我们需要告诉排序函数在比较它们时对每对字典对象使用什么键。每个字典的键只是其(键,值)对的排序列表。
key 函数为每个字典计算一个键,如下所示:
>>> dict_a0 = list_dict_a[0]
>>> key_func(dict_a0)
[('expiration_date', ''), ('identifier_country', ''), ('identifier_number', 'Male'), ('identifier_type', 'Gender'), ('issue_date', '')]
脚注
为了使这个(键,值)对列表能够与其他字典的列表进行比较,必须将 None
值转换为空字符串。这允许 None 值与其他非 None 值进行比较。
上述解决方案的基本假设是,您的案例中的所有字典值都是字符串或 None
,并且“空”值始终表示为 None
(而不是例如空字符串)。如果不是这种情况,则必须相应地调整 key_func()
以确保生成的列表对于数据中预期的任何 dict 值始终相互比较。
此外,对于大型字典,此键函数可能并不理想,因为键对的比较速度太慢。因此,最好为每个字典计算一个唯一的哈希值(但对于比较相等的字典计算相同的哈希值)。
关于python - 排序和比较 Dicts Python 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47913215/