python去掉字典重复项_如何从Python中的列表中删除重复的字典?

So I have a neat list of dictionaries sorted by Matchcode. Now I just need to iterate over the list, accessing the list[dictionary][key] and deleting duplicates when two key values match.

我还不完全确定这意味着什么。听起来你说它们将始终按照你想要用来统一的相同键进行排序。如果是这样,您可以使用itertools recipes中的unique_justseen,使用您在sort中使用的相同键功能,例如itemgetter(key)。

使用已编辑问题中的示例list_of_dicts:

>>> list(unique_justseen(list_of_dicts, key=itemgetter('Matchcode')))

[{'ID': '0001',

'Matchcode': 'SolarUSA, Something Street, Somewhere State, Whatev Zip',

'Organization': 'SolarUSA',

'Owner': 'Timothy Black'},

{'ID': '0003',

'Matchcode': 'Zapotec, Something Street, Somewhere State, Whatev Zip',

'Organization': 'Zapotec',

'Owner': 'Simeon Yurrigan'}]

如果它们按照我们无法识别的那个键的不同键进行排序,则它们被排序的事实根本不相关,并且unique_justseen将不起作用:

>>> list_of_dicts.sort(key=itemgetter('Owner'))

>>> list(unique_justseen(list_of_dicts, key=itemgetter('Matchcode')))

[{'ID': '0002',

'Matchcode': 'SolarUSA, Something Street, Somewhere State, Whatev Zip',

'Organization': 'SolarUSA',

'Owner': 'Johen Wilheim'},

{'ID': '0003',

'Matchcode': 'Zapotec, Something Street, Somewhere State, Whatev Zip',

'Organization': 'Zapotec',

'Owner': 'Simeon Yurrigan'},

{'ID': '0001',

'Matchcode': 'SolarUSA, Something Street, Somewhere State, Whatev Zip',

'Organization': 'SolarUSA',

'Owner': 'Timothy Black'}]但是你只需要使用unique_everseen配方:

>>> list_of_dicts.sort(key=itemgetter('Owner'))

>>> list(unique_everseen(list_of_dicts, key=itemgetter('Matchcode')))

[{'ID': '0002',

'Matchcode': 'SolarUSA, Something Street, Somewhere State, Whatev Zip',

'Organization': 'SolarUSA',

'Owner': 'Johen Wilheim'},

{'ID': '0003',

'Matchcode': 'Zapotec, Something Street, Somewhere State, Whatev Zip',

'Organization': 'Zapotec',

'Owner': 'Simeon Yurrigan'}](当然这次我们有0002而不是0001,因为在Owner上排序之后,它现在是Matchcode而不是第二个的第一个值。)

字典不可清除的事实在这里不相关,因为配方只是将关键函数的结果存储在它们的集合中,因此只要存储在关键字key中的值是可清除的,一切都很好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值