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中的值是可清除的,一切都很好。