Python extract max value from nested dictionary

2024/10/14 3:21:25

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?

Answer

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
>>> 
https://en.xdnf.cn/q/69459.html

Related Q&A

Exponential Decay on Python Pandas DataFrame

Im trying to efficiently compute a running sum, with exponential decay, of each column of a Pandas DataFrame. The DataFrame contains a daily score for each country in the world. The DataFrame looks lik…

TensorFlow - why doesnt this sofmax regression learn anything?

I am aiming to do big things with TensorFlow, but Im trying to start small. I have small greyscale squares (with a little noise) and I want to classify them according to their colour (e.g. 3 categories…

Extended example to understand CUDA, Numba, Cupy, etc

Mostly all examples of Numba, CuPy and etc available online are simple array additions, showing the speedup from going to cpu singles core/thread to a gpu. And commands documentations mostly lack good …

Python 2 newline tokens in tokenize module

I am using the tokenize module in Python and wonder why there are 2 different newline tokens:NEWLINE = 4 NL = 54Any examples of code that would produce both tokens would be appreciated.

Prevent encoding errors in Python

I have scripts which print out messages by the logging system or sometimes print commands. On the Windows console I get error messages likeTraceback (most recent call last):File "C:\Python32\lib\l…

How do I get the operating system name in a friendly manner using Python 2.5?

I tried:print os.nameAnd the output I got was::ntHowever, I want output more like "Windows 98", or "Linux".After suggestions in this question, I also tried:import os print os.name i…

Extend dataclass __repr__ programmatically

Suppose I have a dataclass with a set method. How do I extend the repr method so that it also updates whenever the set method is called: from dataclasses import dataclass @dataclass class State:A: int …

find least common denominator for list of fractions in python

I have a list of fractionsfrom fractions import Fractionfractions_list=[Fraction(3,14),Fraction(1,7),Fraction(9,14)]The output should be a list with the numerators for each fraction, then the denominat…

How to configure uwsgi to encode logging as json except app output

Im running uwsgi around a Python Flask webapp with these options (among others) to get JSON-encoded log records on stdout:fmt=${"timestamp": "${strftime:%FT%TZ}", "level":…

Testing aiohttp client with unittest.mock.patch

Ive written a simple HTTP client using aiohttp and Im trying to test it by patching aiohttp.ClientSession and aiohttp.ClientResponse. However, it appears as though the unittest.mock.patch decorator is …