简体   繁体   中英

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?

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
>>> 

Take every number at capacity and check for the max:

>>> myDict =  {'2015-01-01': {'time': '8', 'capacity': '5'}, 
  '2015-01-02': {'time': '8', 'capacity': '7'},
  '2015-01-03': {'time': '8', 'capacity': '8'} }
>>> max_capacity = max([int(i['capacity']) for i in myDict.values()])
>>> max_capacity
8

You could do this a long boring way

print max(input_dict.items(), key=lambda v: int(input_dict[v[0]]['capacity']))[1]['capacity']

But wait why did this max(input_dict, key=lambda v: input_dict[v]['capacity']) not work OMG the reason to that is

When you call max(input_dict, key=lambda v: input_dict[v]['capacity']) input_dict dicts keys are called so you get the output which is the key with highest capacity

Notes:

  • What I have done in my max function is I called dictionaries item function which returns the key and value in List of set since I have used a list of set as test sample I will get a set as output from max function.

  • The first value would be the key and the second value would be the value

  • So after applying the max function I would get a set with two values one is key and the other is it's corresponding value so you could use [1]['capacity'] to get capacity value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM