Tom Anderson
Tom Anderson

Reputation: 37

Find maximum value in a nested dictionary

I am having trouble understanding how to pull the maximum value of a nested dictionary when it is structured as so:

dict = {'City': {1: {'avg_dur': 10.58568297387339,
                 'n_trips': 1901,
                 'tot_dur': 20123.383333333313},
             2: {'avg_dur': 12.25947507658035,
                 'n_trips': 2394,
                 'tot_dur': 29349.183333333356},
             3: {'avg_dur': 12.95495652953303,
                 'n_trips': 3719,
                 'tot_dur': 48179.48333333334}}}

I am trying to extract the key for the maximum 'avg_trips' function. In the snippet above, I would expect the answer to return 3. I think I need to use lambda here, but I'm not sure how that works with nested dictionaries to this level.

Upvotes: 0

Views: 2027

Answers (2)

sacuL
sacuL

Reputation: 51335

You could also sort the keys by n_trips and take the last one:

>>> sorted(mydict['City'].keys(), key=lambda x: mydict['City'][x]['n_trips'])[-1]
3

Upvotes: 0

Rakesh
Rakesh

Reputation: 82765

Use max with key

Ex:

dict = {'City': {1: {'avg_dur': 10.58568297387339,
                 'n_trips': 1901,
                 'tot_dur': 20123.383333333313},
             2: {'avg_dur': 12.25947507658035,
                 'n_trips': 2394,
                 'tot_dur': 29349.183333333356},
             3: {'avg_dur': 12.95495652953303,
                 'n_trips': 3719,
                 'tot_dur': 48179.48333333334}}}

print(max(dict["City"].items(), key=lambda x: x[1]['n_trips'])[0])

Output:

3

Upvotes: 2

Related Questions