我有一个字典列表,其中一个键值不唯一:
arr = [{'host': '144.217.103.15', 'port': 3000},
{'host': '158.69.115.201', 'port': 8080},
{'host': '144.217.103.15', 'port': 1020},]
我想让这个给定的数组在' host'方面独一无二。键,以便最终输出为:
result = [{'host': '158.69.115.201', 'port': 8080},
{'host': '144.217.103.15', 'port': 1020},]
或者可能是:
result = [{'host': '144.217.103.15', 'port': 3000},
{'host': '158.69.115.201', 'port': 8080},]
Pythonic这样做的方式是什么?
答案 0 :(得分:4)
您可以转换为dict并提取值:
>>> { d['host']: d for d in arr }.values()
[{'host': '144.217.103.15', 'port': 1020}, {'host': '158.69.115.201', 'port': 8080}]
对于Python3,您可以将dict_values
转换为list
:
>>> list({d['host']: d for d in arr}.values())
[{'host': '144.217.103.15', 'port': 1020}, {'host': '158.69.115.201', 'port': 8080}]
如果您想保留原始订单(减去host
重复项),您可以使用OrderedDict:
>>> from collections import OrderedDict
>>> list(OrderedDict( (d['host'], d) for d in arr).values())
[{'host': '144.217.103.15', 'port': 1020}, {'host': '158.69.115.201', 'port': 8080}]
最后,如果您想要一个包含唯一host
和 port
的词典列表,您可以使用元组作为键:
>>> list(OrderedDict(((d['host'], d['port']), d) for d in arr).values())
[{'host': '144.217.103.15', 'port': 3000}, {'host': '158.69.115.201', 'port': 8080}, {'host': '144.217.103.15', 'port': 1020}]
答案 1 :(得分:1)
保留第一个条目:
arr = [{'host': '144.217.103.15', 'port': 3000},
{'host': '158.69.115.201', 'port': 8080},
{'host': '144.217.103.15', 'port': 1020},]
hosts = set()
out = []
for entry in arr:
if not entry['host'] in hosts:
out.append(entry)
hosts.add(entry['host'])
print(out)
#[{'host': '144.217.103.15', 'port': 3000}, {'host': '158.69.115.201', 'port': 8080}]