Home > Mobile >  Calculate max in a nested dictionary
Calculate max in a nested dictionary

Time:01-13

I have a nested dictionary like this:

time_values = {
    "A": {
        "time": {
                    "B": 2,
                    "C": 3,
                    "D": 5
                }
         },
    "B": {
        "time": {
                    "A": 7,
                    "C": 2,
                    "D": 3
                }
         },
    "C": {
        "time": {
                    "A": 8,
                    "B": 9,
                    "D": 2
                }
         },
    "D": {
        "time": {
                    "A": 7,
                    "B": 2,
                    "C": 3
                }
         }
    }

and I want to calculate the max among all times. I think the problem here is that the only common key among the dictionaries is time, all the others can change as they are the travel time between 2 points.

The initial code was:

max_time = 0

for station in time_values:
    for other_station in time_values[station]["time"]:
        if time_values[station]["time"][other_station] > max_time:
            max_time = time_values[station]["time"][other_station]

but I would like to make it more pythonic using the dictionary in a better way.

I was trying something like this:

time_list = []

for _, b in time_values.items():
    time_list.append(list(b.get("time").values()))

max_value = max(list(itertools.chain(*time_list)))

but I am not sure if it's a "better" code...

Any idea?

CodePudding user response:

A one liner that finds the max of every subdict, and then finds the max of all of those.

print(max([max(v['time'].values()) for v in time_values.values()]))
  • Related