python - 按所有键的唯一性对字典列表进行排序

标签 python list sorting dictionary

用这个把我的头发拔掉。

我有一个字典列表,每个唯一条目都没有唯一的主 ID 键(字典是动态构建的):

dicts = [{'firstname': 'john', 'lastname': 'doe', 'code': 'crumpets'},
         {'firstname': 'john', 'lastname': 'roe', 'code': 'roe'},
         {'firstname': 'john', 'lastname': 'doe', 'code': 'crumpets'},
         {'firstname': 'thom', 'lastname': 'doe', 'code': 'crumpets'},
]

我如何着手过滤掉像这样的字典列表,其中删除了列表中的任何重复 {}?所以我需要检查所有三个字典键是否与列表中的另一个键匹配......如果满足该检查,则从 dict 中丢弃它。

因此,对于我上面的示例,第一个和第三个“条目”需要删除,因为它们是重复的。

最佳答案

您使用从字典创建卡住集并将它们放入一个集中以删除重复项:

dcts = [dict(d) for d in set(frozenset(d.items()) for d in dcts)]
print(dcts)

[{'code': 'roe', 'firstname': 'john', 'lastname': 'roe'},
 {'code': 'crumpets', 'firstname': 'thom', 'lastname': 'doe'},
 {'code': 'crumpets', 'firstname': 'john', 'lastname': 'doe'}]

如果您选择删除所有重复项,您可以使用计数器:

from collections import Counter

dcts = [dict(d) for d, cnt in Counter(frozenset(d.items()) for d in dcts).items() 
                                                                      if cnt==1]
print(dcts)

[{'code': 'roe', 'firstname': 'john', 'lastname': 'roe'},
 {'code': 'crumpets', 'firstname': 'thom', 'lastname': 'doe'}]

关于python - 按所有键的唯一性对字典列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44627424/

相关文章:

python - PonyORM (Python) "Value was updated outside of current transaction"但事实并非如此

python - 在Python中,如何计算电子邮件地址列表中 '1'的数量?

c# - 如何最好地删除 C# 中循环中的列表项

perl - 在 Perl 中根据一项的值对二维数组进行排序,但有异常(exception)

python - 为什么 python 即使在刷新和使用 -u 时也会继续缓冲标准输出?

python - Django 用户 : get list of group, 或如何将 MultipleChoiceField 转换为 ChoiceField

python - 在 Python 中读取原始二进制图像

python - 调用列表中元素的析构函数

Java排序数据结构

javascript - 对对象的代理数组进行排序,localeCompare 不是函数