如何在字典列表中找到公共键的最小值/最大值? [英] How to find the min/max value of a common key in a list of dicts?
本文介绍了如何在字典列表中找到公共键的最小值/最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的字典列表:
I have a list of dictionaries like so:
[{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]
我想找到 min()
和 max()
的价格.现在,我可以使用带有 lambda 表达式的键轻松地对其进行排序(如另一篇 Stack Overflow 帖子中所述),因此如果没有其他方法,我不会被卡住.然而,据我所知,Python 中几乎总是有一种直接的方式,所以这是一个让我多学习一点的机会.
I want to find the min()
and max()
prices. Now, I can sort this easily enough using a key with a lambda expression (as found in another Stack Overflow post), so if there is no other way I'm not stuck. However, from what I've seen there is almost always a direct way in Python, so this is an opportunity for me to learn a bit more.
推荐答案
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'])
这不仅会告诉您最高价格是多少,还会告诉您哪个商品最贵.
This tells you not just what the max price is but also which item is most expensive.
这篇关于如何在字典列表中找到公共键的最小值/最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文