如何在字典列表中查找公共键的最小/最大值?

问题描述 投票:0回答:6

我有一个像这样的字典列表:

[{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]

我想查找

min()
max()
价格。现在,我可以使用带有 lambda 表达式的键(如另一篇 Stack Overflow 帖子中所示)轻松地对此进行排序,因此如果没有其他方法,我就不会陷入困境。然而,据我所知,Python 中几乎总是有直接的方法,所以这对我来说是一个学习更多知识的机会。

python list dictionary max min
6个回答
375
投票
lst = [{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]

maxPricedItem = max(lst, key=lambda x:x['price'])
minPricedItem = min(lst, key=lambda x:x['price'])

这不仅告诉您最高价格是多少,还告诉您哪件商品最贵。


75
投票

有多种选择。这是一个简单的方法:

seq = [x['the_key'] for x in dict_list]
min(seq)
max(seq)

[编辑]

如果您只想遍历列表一次,您可以尝试此操作(假设值可以表示为

int
s):

import sys

lo,hi = sys.maxint,-sys.maxint-1
for x in (item['the_key'] for item in dict_list):
    lo,hi = min(x,lo),max(x,hi)

54
投票

我认为最直接(也是最Pythonic)的表达方式是这样的:

min_price = min(item['price'] for item in items)

这避免了对列表进行排序的开销——并且通过使用生成器表达式而不是列表理解——实际上也避免了创建任何列表。高效、直接、可读...Pythonic!


15
投票

一个答案是将您的字典映射到生成器表达式中感兴趣的值,然后应用内置函数

min
max

myMax = max(d['price'] for d in myList)
myMin = min(d['price'] for d in myList)

5
投票

也可以用这个:

from operator import itemgetter

lst = [{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]  
max(map(itemgetter('price'), lst))

0
投票

并添加到这个伟大的页面:通用便捷功能中的最佳答案:


def takeMaxFromDictList(listOfDicts: list, keyToLookAt: str) -> dict:
  return max( listOfDicts, key=lambda x: x[keyToLookAt] )

# -------------------------------------------------------------------

examplelist = [{'score': 0.995, 'label': 'buildings'},
               {'score': 0.002, 'label': 'mountain'},
               {'score': 0.001, 'label': 'forest'}]
 
print ( takeMaxFromDictList(examplelist, 'score') )

>>> {'score': 0.995, 'label': 'buildings'}

© www.soinside.com 2019 - 2024. All rights reserved.