eta*_*luz 2 python dictionary python-3.x
我有一个字典列表,其中的键值之一不是唯一的:
arr = [{'host': '144.217.103.15', 'port': 3000},
{'host': '158.69.115.201', 'port': 8080},
{'host': '144.217.103.15', 'port': 1020},]
Run Code Online (Sandbox Code Playgroud)
我想使给定的数组在“主机”键方面唯一,以便最终输出为:
result = [{'host': '158.69.115.201', 'port': 8080},
{'host': '144.217.103.15', 'port': 1020},]
Run Code Online (Sandbox Code Playgroud)
或者可能是:
result = [{'host': '144.217.103.15', 'port': 3000},
{'host': '158.69.115.201', 'port': 8080},]
Run Code Online (Sandbox Code Playgroud)
Python的这样做方式是什么?
您可以将其转换为字典并提取值:
>>> { d['host']: d for d in arr }.values()
[{'host': '144.217.103.15', 'port': 1020}, {'host': '158.69.115.201', 'port': 8080}]
Run Code Online (Sandbox Code Playgroud)
对于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}]
Run Code Online (Sandbox Code Playgroud)
如果要保留原始订单(减去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}]
Run Code Online (Sandbox Code Playgroud)
最后,如果要使用具有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}]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
207 次 |
| 最近记录: |