如何检查和从字典中的项目删除重复值?我有一个大的数据集,所以我在寻找一种有效的方法。以下是包含重复的字典值的示例:
'word': [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]
需要成为
'word': [('769817', [6]), ('769819', [4, 10])]
这个问题实际上可以归结为从unhashable类型的列表,为此转换为一组不能够删除重复。
一种可能的方法是在电流值来检查会员,同时建立一个新的列表值。
d = {'word': [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]}
for k, v in d.items():
new_list = []
for item in v:
if item not in new_list:
new_list.append(item)
d[k] = new_list
或者,使用groupby()
一个更简洁的答案,虽然可能比较慢(名单必须先排序,如果是的话,那是不是做了成员资格检查速度更快)。
import itertools
d = {'word': [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]}
for k, v in d.items():
v.sort()
d[k] = [item for item, _ in itertools.groupby(v)]
输出 - > {'word': [('769817', [6]), ('769819', [4, 10])]}
你有一个列表,而不是一本字典。 Python字典可能只有一个每个键值。尝试
my_dict = dict([('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])])
结果:
{'769817': [6], '769819': [4, 10]}
Python字典。欲了解更多信息https://docs.python.org/3/tutorial/datastructures.html#dictionaries
这个怎么样:我只是专注于列表中的一部分:
>>> s = [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]
>>> [(x,y) for x,y in {key: value for (key, value) in s}.items()]
[('769817', [6]), ('769819', [4, 10])]
>>>
删除线适用于原来的问题编辑之前,为后人留下了:
你不使用dict
所有,只是两list
s,其中每个tuple
第二个元素本身是tuple
的list
。如果你真的想要一个dict
,
dict([('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])])
将它转换,并通过关键uniquify(所以你最终与{'769817': [6], '769819': [4, 10]}
,尽管它失去了秩序,并没有注意值(子list
s)是否是唯一的或不是(它只是让最后的配对对于给定的键)。
如果您需要uniquify相邻重复(其中的值是唯一重要的),而维持秩序,并且不希望/需要一个真正的dict
,使用itertools.groupby
:
import itertools
nonuniq = [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]
uniq = [k for k, g in itertools.groupby(nonuniq)]
# uniq is [('769817', [6]), ('769819', [4, 10])]
# but it wouldn't work if the input was
# [('769819', [4, 10]), ('769817', [6]), ('769819', [4, 10])]
# because the duplicates aren't adjacent
如果您需要塌陷不相邻的重复,也不需要维持秩序(或排序顺序是罚款),你可以使用groupby
得到O(n log n)
解决方案(而不是创造一个新的列表天真的解决方案,并避免重复用检查在O(n^2)
复杂性在新的列表存在,或set
基础的解决方案,这将是O(n)
,但需要你的子list
s转换成你的数据tuple
s,使他们可哈希):
# Only difference is sorting nonuniq before grouping
uniq = [k for k, g in itertools.groupby(sorted(nonuniq))]
# uniq is [('769817', [6]), ('769819', [4, 10])]
your_list = [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]
new = []
for x in your_list:
if x not in new: new.append(x)
print(new)
>>>[('769817', [6]), ('769819', [4, 10])]
您可以uniqify基于它们所产生的哈希值的项目。哈希可以是任何东西,一个排序json.dumps
,或cPickle.dumps
。如需要这一个衬垫可以uniqify你的字典。
>>> d = {'word': [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]}
>>> import json
>>> { k: { json.dumps(x,sort_keys = True):x for x in v}.values() for k,v in d.iteritems()}
{'word': [('769817', [6]), ('769819', [4, 10])]}
那个怎么样?
def remove_duplicates(d: dict):
unique_values = set(d.values())
o = {}
for k, v in d.items():
if v in unique_values:
o[k] = v
unique_values.remove(v)
return o