如果特定键值(即键:x['src_ip']
)多次出现,我将如何在Python中重复删除字典列表?
x = [{"_serial": "0", "src_ip": "5.5.5.5"},
{"_serial": "1", "src_ip": "5.5.5.5"},
{"_serial": "2", "src_ip": "1.1.1.2"},
{"_serial": "3", "src_ip": "1.2.6.4"}]
我基本上希望将以下列表作为最终结果:
x = [{"_serial": "0", "src_ip": "5.5.5.5"},
{"_serial": "2", "src_ip": "1.1.1.2"},
{"_serial": "3", "src_ip": "1.2.6.4"}]
答案 0 :(得分:3)
您可以使用itertools.groupby()
和next()
来实现此目标:
from itertools import groupby
result = [next(v) for k, v in groupby(x, lambda d: d["src_ip"])]
<强> result
强>:
[{'_serial': '0', 'src_ip': '5.5.5.5'},
{'_serial': '2', 'src_ip': '1.1.1.2'},
{'_serial': '3', 'src_ip': '1.2.6.4'}]
原样,仅当您的列表已在d["src_ip"]
上排序时,此功能才有效。如果没有,请先排序:
def key(d):
return d["src_ip"]
result = [next(v) for k, v in groupby(sorted(x, key=key), key)]
答案 1 :(得分:1)
对于此特定输入和所需输出,您可以尝试:
x = [{"_serial": "0", "src_ip": "5.5.5.5"},
{"_serial": "1", "src_ip": "5.5.5.5"},
{"_serial": "2", "src_ip": "1.1.1.2"},
{"_serial": "3", "src_ip": "1.2.6.4"}]
values = []
new_x = []
for d in x:
if not d['src_ip'] in values:
new_x.append(d)
values.append(d['src_ip'])
print(new_x)