[英]Python - Get first value from dictionary with matching keys
d= {'Time': '1', 'Key':'val1'}
d1={'Time':'2', 'Key':'val1'}
d2={'Time':'3', 'Key':'val1'}
d3={'Time':'3', 'Key':'val2'}
d3={'Time':'8', 'Key':'val2'}}
How to print the output in this format:如何以这种格式打印输出:
output=[{Time': '1', 'Key':'val1'}, {'Time':'3', 'Key':'val2'}]
How do I remove the duplicate values by a single key, value combination and print the first occurrence of the combination.如何通过单个键、值组合删除重复值并打印组合的第一次出现。 Thanks for you help.
谢谢你的帮助。
lst = [
{'Time': '1', 'Key':'val1'},
{'Time':'2', 'Key':'val1'},
{'Time':'3', 'Key':'val1'},
{'Time':'3', 'Key':'val2'},
{'Time':'8', 'Key':'val2'}
]
Using a for
loop with any
for
any
使用for
循环
res = []
for i in lst:
if not any(i['Key'] in x.values() for x in res):
res.append(i)
else:
pass
print(res)
# [{'Time': '1', 'Key': 'val1'}, {'Time': '3', 'Key': 'val2'}]
Can be done with itertools.groupby
可以用
itertools.groupby
完成
res = []
for _, g in groupby(lst, key = lambda x: x['Key']):
res.append(list(g)[0])
itertools.groupby
with list comprehension and operator.itemgetter
itertools.groupby
与列表itertools.groupby
和operator.itemgetter
from itertools import groupby
from operator import itemgetter
res = [list(g)[0] for _, g in groupby(lst, key=itemgetter('Key'))]
You can also collect items in a dictionary as you reduce
and only add if the key isn't present:您还可以在
reduce
收集字典中的项目,并且仅在键不存在时才添加:
from functools import reduce
lst = [
{'Time': '1', 'Key':'val1'},
{'Time':'2', 'Key':'val1'},
{'Time':'3', 'Key':'val1'},
{'Time':'3', 'Key':'val2'},
{'Time':'8', 'Key':'val2'}
]
def collect_if_absent(acc, d):
if d['Key'] not in acc:
acc[d['Key']] = d
return acc
res = list(reduce(collect_if_absent, lst, {}).values())
print(res)
# [{'Time': '1', 'Key': 'val1'}, {'Time': '3', 'Key': 'val2'}]
This should take O(n) .这应该需要O(n) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.