0

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'}]

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Rik
  • 1,870
  • 3
  • 22
  • 35

2 Answers2

1

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'}]
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
0

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
ToughMind
  • 987
  • 1
  • 10
  • 28