Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python extract max value from nested dictionary

I have a nested dictionary of the form:

 {'2015-01-01': {'time': '8', 'capacity': '5'}, 
  '2015-01-02': {'time': '8', 'capacity': '7'},
  '2015-01-03': {'time': '8', 'capacity': '8'} etc}

The dictionary is created from a csv file using dictreader. What I would like to be able to do is return the maximum value of capacity. So in this case 8.

I can use:

for k,v in input_dict.items():
    if temp_max < int(v['capacity']):
        temp_max = int(v['capacity'])

which works but I wondered if there was a neater method? I've searched and found methods to extract the top level key associated with the maximum value which is of course not what I need. See below:

max(input_dict, key=lambda v: input_dict[v]['capacity'])

which would return '2015-01-03', So I imagine there is a simple mod to the above one liner that will give me what I need but is has me stumped!

Any ideas?

like image 761
Pete Avatar asked Nov 25 '15 11:11

Pete


People also ask

How do you find the maximum value in a dictionary?

Use max() with the key parameter set to dict. get() to find and return the key of the maximum value in the given dictionary. Use min() with the key parameter set to dict. get() to find and return the key of the minimum value in the given dictionary.

How do you find the max value in Python?

Python max() FunctionThe max() function returns the item with the highest value, or the item with the highest value in an iterable. If the values are strings, an alphabetically comparison is done.

How do I return a key to the highest value in Python?

The simplest way to get the max value of a Python dictionary is to use the max() function. The function allows us to get the maximum value of any iterable.

What is .get in Python?

Python Dictionary get() Method The get() method returns the value of the item with the specified key.


1 Answers

You want

max(int(d['capacity']) for d in input_dict.values())

Explanation:

If you don't care about the keys, just iterate over the nested dicts (IOW the outer dict's values)

Also your inner dicts "capacity" values are stored as strings, I assume you want to test the integer value. To find out the difference check this:

>>> max(["1", "5", "18", "01"])
'5'
>>> max([1, 5, 18, 01])
18
>>> 
like image 143
bruno desthuilliers Avatar answered Nov 03 '22 05:11

bruno desthuilliers