In List of Dicts find min value of a common Dict field

0 votes

I have a list of dictionaries like so:

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

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 SO article), 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.

Aug 30, 2018 in Python by bug_seeker
• 15,550 points

2 answers to this question.

0 votes

There are several options. Here is a straight-forward one:

seq = [x['the_key'] for x in dict_list]


If you only wanted to iterate through the list once, you could try this (assuming the values could be represented as ints):

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)
answered Aug 30, 2018 by Priyaj
• 58,100 points
0 votes
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'])
answered Aug 31, 2018 by Omkar
• 69,090 points

Related Questions In Python

+2 votes
2 answers

In a list of dictionaries, how can I find the minimum calue in a common dictionary field.

There are several options. Here is a ...READ MORE

answered Apr 10, 2018 in Python by charlie_brown
• 7,780 points
0 votes
1 answer

How to find the index of a particular value in a dataframe?

First, use the dataframe to match the ...READ MORE

answered Apr 8, 2019 in Python by Esha
0 votes
1 answer

How to find the value of a row in a csv file in python?

If you want to find the value ...READ MORE

answered May 20, 2019 in Python by Sanam
0 votes
4 answers

how to sort a list of numbers without using built-in functions like min, max or any other function?

I guess you are trying to do ...READ MORE

answered Dec 11, 2020 in Python by Rajiv
• 8,880 points
0 votes
1 answer

Creating a new dict in Python

Call dict with no parameters new_dict = dict() or simply write new_dict ...READ MORE

answered Sep 17, 2018 in Python by Priyaj
• 58,100 points
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,869 views
–1 vote
2 answers

How to find the size of a string in Python?

following way to find length of string  x ...READ MORE

answered Mar 29, 2019 in Python by rajesh
• 1,230 points
0 votes
1 answer

Convert string list of dict from csv into JSON object in python

You can use the ast module Ex: import ast s = """[{'10': ...READ MORE

answered Sep 12, 2018 in Python by Priyaj
• 58,100 points