如果嵌套字典前面没有键,我现在可以删除重复项。使用此函数的dict列表的一个示例是:
[{'asndb_prefix': '164.39.xxx.0/17',
'cidr': '164.39.xxx.0/17',
'cymru_asn': 'XXX',
'cymru_country': 'GB',
'cymru_owner': 'XXX , GB',
'cymru_prefix': '164.39.xxx.0/17',
'ips': ['164.39.xxx.xxx'],
'network_id': '164.39.xxx.xxx/24',},
{'asndb_prefix': '54.192.xxx.xxx/16',
'cidr': '54.192.0.0/16',
'cymru_asn': '16509',
'cymru_country': 'US',
'cymru_owner': 'AMAZON-02 - Amazon.com, Inc., US',
'cymru_prefix': '54.192.144.0/22',
'ips': ['54.192.xxx.xxx', '54.192.xxx.xxx'],
'network_id': '54.192.xxx.xxx/24',
}]
def remove_dict_duplicates(list_of_dicts):
"""
"" Remove duplicates in dict
"""
list_of_dicts = [dict(t) for t in set([tuple(d.items()) for d in list_of_dicts])]
# remove the {} before and after - not sure why these are placed as
# the first and last element
return list_of_dicts[1:-1]
但是,我希望能够删除基于键和字典内所有相关值的重复项。所以如果同一个键有不同的值,我不想删除它,但如果有一个完整的副本,然后删除它。在
^{pr2}$我该怎么做?谢谢您。在
如果结果中的顺序不重要,则可以使用集合将dict转换为冻结集来删除重复项:
这假设最里面的dict的所有值都是散列的。在
放弃订单可能会加速大型列表。 例如,创建一个包含100000个元素的列表:
^{pr2}$反复检查结果列表中的重复项需要相当长的时间:
我的方法是,使用set更快:
要从dict列表中删除重复项,请执行以下操作:
相关问题 更多 >
编程相关推荐