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?
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.
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.
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.
Python Dictionary get() Method The get() method returns the value of the item with the specified key.
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
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With