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
  • 95,415
  • 23
  • 151
  • 231
Rik
  • 1,710
  • 2
  • 20
  • 31

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
  • 11,623
  • 3
  • 23
  • 37
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
  • 879
  • 1
  • 8
  • 23