从字典列表中返回在特定键中具有最高值的字典 [英] Return the dictionary from a list of dictionaries with the highest value in a specific key
问题描述
我在python中有以下字典列表:
I have the following list of dictionaries in python:
data = [{'flag': 'one', 'timestamp': 20190710},
{'flag': 'one', 'timestamp': 20190711},
{'flag': 'two', 'timestamp': 20190712},
{'flag': 'two', 'timestamp': 20190709}]
我想返回在键 timestamp
中具有最高值并且在键 flag
中具有值 one
的字典.
I would like to return the dictionary with the the highest value in the key timestamp
and with the value one
in the key flag
.
我在这里做了类似的事情:
I have done something similar here:
但是不能使其在此新设置中起作用.
But cannot make it work in this new set-up.
推荐答案
您可以将 max()
内置函数与自定义 key =
一起使用.在此之前,我们仅对键为'flag'
== 'one'
:
You could use max()
built-in function with custom key=
. Before that, we filter the dictionary only for items with key 'flag'
== 'one'
:
data = [{'flag': 'one', 'timestamp': 20190710},
{'flag': 'one', 'timestamp': 20190711},
{'flag': 'two', 'timestamp': 20190712},
{'flag': 'two', 'timestamp': 20190709}]
print(max((i for i in data if i['flag'] == 'one'), key=lambda k: k['timestamp']))
打印:
{'flag': 'one', 'timestamp': 20190711}
什么更快的快速基准测试-首先进行过滤或在整个列表中找到最大值:
Quick benchmark of what's faster - doing the filtration first or finding the max in whole list:
from random import choice,randint
data = []
for i in range(10000):
data.append({'flag': choice(['one', 'two']), 'timestamp': randint(1, 1_000_000)})
def fn1():
return max(data, key=lambda x: (x["flag"] == 'one', x["timestamp"]))
def fn2():
return max((i for i in data if i['flag'] == 'one'), key=lambda k: k['timestamp'])
from timeit import timeit
t1 = timeit(lambda: fn1(), number=1_000)
t2 = timeit(lambda: fn2(), number=1_000)
print(t1)
print(t2)
打印:
1.5405012619994523
0.8562619980002637
这意味着首先进行过滤会更快.
Which means doing the filtration first is faster.
这篇关于从字典列表中返回在特定键中具有最高值的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!