Rik
Rik

Reputation: 1977

Get the max of a nested dictionary

I have the following data structure:

{'923874rksd9293': {'animated': (1, 5.0),'romance':(1, 4.0),'superhero':(1,3.0)}}

and I'd like to get the category with the maximum of the floating point value, here animated with 5.0. Is there a pythonic way to do this? There may be more than one id and it would be put into an array. Thanks

so the return value would be: [{'id':'923874rksd9293','genre':'animated'}]

Upvotes: 0

Views: 61

Answers (2)

ToughMind
ToughMind

Reputation: 1009

you can try code below:

data = {'923874rksd9293': {'animated': (1, 5.0),'romance':(1, 4.0),'superhero':(1,3.0)}}

for id, val in data.items():
    maxType = max(val, key=lambda x:max(val[x]))

    print(f"id:{id}, genre:{maxType}")

The output is

id:923874rksd9293, genre:animated

Upvotes: 0

Adam.Er8
Adam.Er8

Reputation: 13393

you can use max with a custom key function, to choose the max genre based on the value of the tuple mapped by it.

try this:

d = {'1111': {'animated': (1, 5.0),'romance':(1, 4.0),'superhero':(1,3.0)},
     '2222': {'genreone': (1, 3.5),'genretwo':(1, 4.8),'superhero':(1,4.0)}}

result = [{"id":key, "genre":max(inner.keys(), key=lambda k:inner[k][1])} for key,inner in d.items()]

print(result)

Output:

[{'id': '1111', 'genre': 'animated'}, {'id': '2222', 'genre': 'genretwo'}]

Upvotes: 1

Related Questions