Python-使用匹配的键从字典中获取第一个值

时间:2018-10-15 21:59:02

标签: python python-3.x dictionary

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'}}

如何以这种格式打印输出:

output=[{Time': '1', 'Key':'val1'}, {'Time':'3', 'Key':'val2'}]

如何通过单个键,值组合删除重复的值并打印该组合的首次出现。感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

lst =  [
    {'Time': '1', 'Key':'val1'},
    {'Time':'2', 'Key':'val1'},
    {'Time':'3', 'Key':'val1'},
    {'Time':'3', 'Key':'val2'},
    {'Time':'8', 'Key':'val2'}
]

使用for的{​​{1}}循环

any

可以通过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'}]

完成
itertools.groupby

res = [] for _, g in groupby(lst, key = lambda x: x['Key']): res.append(list(g)[0]) ,具有列表理解和itertools.groupby

operator.itemgetter

答案 1 :(得分:0)

您也可以像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'}]

这应该花费 O(n)