这是我当前的词典列表:
list1 = [{"one" : 1, "too": 2, "three": 3}, {"one" : 10, "too": 20, "three": 30} , {"one" : 1, "too": 26, "three": 35}, {"one" : 1, "too": 236, "three": 365}]
我想基于键“ one”从列表中删除所有重复字典。 这意味着在键“一个”中该列表的另一个字典中的值是相同的,将其删除。 我希望输出为:
list1 = [{"one" : 1, "too": 2, "three": 3}, {"one" : 10, "too": 20, "three": 30}]
答案 0 :(得分:2)
您应该保留set
键的可见值"one"
。然后,您可以使用如下所示的简单循环或棘手的理解(利用or
运算符的作用):
list1 = [{"one" : 1, "too": 2, "three": 3}, {"one" : 10, "too": 20, "three": 30} , {"one" : 1, "too": 26, "three": 35}, {"one" : 1, "too": 236, "three": 365}]
seen = set()
list1[:] = [seen.add(d["one"]) or d for d in list1 if d["one"] not in seen]
# [{'one': 1, 'too': 2, 'three': 3}, {'one': 10, 'too': 20, 'three': 30}]
切片分配只是确保这是原始列表上的一个突变,例如如果要使用它来修改函数参数。
无论如何,您都应该从头开始构建列表,因为从list
重复删除是反模式的表现很差。
答案 1 :(得分:1)
尝试:
list1 = [{"one" : 1, "too": 2, "three": 3}, {"one" : 10, "too": 20, "three": 30} , {"one" : 1, "too": 26, "three": 35}, {"one" : 1, "too": 236, "three": 365}]
l = [d for index,d in enumerate(list1) if d["one"] not in set(map(lambda x:x["one"],list1[:index]))]
结果:
[{'one': 1, 'too': 2, 'three': 3}, {'one': 10, 'too': 20, 'three': 30}]
答案 2 :(得分:0)
这将为您提供唯一列表以及列表中的唯一键。
代码:
list1 = [{"one" : 1, "too": 2, "three": 3}, {"one" : 10, "too": 20, "three": 30} , {"one" : 1, "too": 26, "three": 35}, {"one" : 1, "too": 236, "three": 365}]
list2=[]
unikey=[]
for i in range(0,len(list1)):
if list1[i]['one']:
if list1[i]['one'] not in unikey:
unikey.append(list1[i]['one'])
list2.append(list1[i])
print('Unique List -> ',list2)
print('Unique Keys -> ', unikey)
结果:
Unique List -> [{'one': 1, 'too': 2, 'three': 3}, {'one': 10, 'too': 20, 'three': 30}]
Unique Keys -> [1, 10]