JLY
JLY

Reputation: 23

Finding the minimum value in a nested dictionary & assigned it to the key [python]

I'm stuck at some point on how to achieve to get which key has got the minimum pb value in the nested dict below.

a = {1230: {'name': 'Jack', 'age': 13, 'pb': 9.3, 'run': 10}, 1241: {'name': 'Sarah', 'age': 6, 'pb': 15.39, 'run': 21}, 1252: {'name': 'Eric', 'age': 6, 'pb': 16.41, 'run': 21}}

I applied the logic of getting all pb and assigned them to a new list using tuple:

reg = []
for i in a.keys():
   b = ( a[reg], a[reg]['pb'] )

Then using the min function to determine which key has the minimum value.

print(min(b, key=b.get))

Then I'm getting an error saying "TypeError: unhashable type: 'list'"

Any idea as to why I am getting this error because I'm changing the list to a tuple already then applying the min function.

Thank you all in advance for your help.

Upvotes: 1

Views: 1150

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could do the following:

a = {1230: {'name': 'Jack', 'age': 13, 'pb': 9.3, 'run': 10}, 1241: {'name': 'Sarah', 'age': 6, 'pb': 15.39, 'run': 21},
     1252: {'name': 'Eric', 'age': 6, 'pb': 16.41, 'run': 21}}

key = min(a, key=lambda x: a[x]['pb'])

print(key)

Output

1230

Upvotes: 5

Related Questions