1

I want maximum scorer from this complicated data, but it shows error, maybe I am doing something wrong here.

students = {
    'harshit':{'score':90, 'age':22},
    'Mohit':{'score':79, 'age':20},
    'Rohit':{'score':99, 'age':29}
}

print((max(students , key= lambda item: item.get('score'))))

I expected the output : Rohit
but here I got an error cox they're saying item is a string but for my case it is also a key

Zankrut Parmar
  • 1,872
  • 1
  • 13
  • 28
Ankit Singh
  • 247
  • 4
  • 14

2 Answers2

3

you probably want this -

students = {
    'harshit':{'score':90, 'age':22},
    'Mohit':{'score':79, 'age':20},
    'Rohit':{'score':99, 'age':29}
}

print((max(students , key= lambda item: students[item].get('score'))))

By lambda you are specifying the key. So students[item] to iterate over the students and then get('score') to get score for a particular entry.

Arnab Roy
  • 619
  • 5
  • 16
0

Ohh I Got it!! Now i'm accessing my key from main dictionary then inside elements

students = {
    'harshit':{'score':9, 'age':22},
    'Mohit':{'score':9, 'age':20},
    'Rohit':{'score':9, 'age':29}
}
print((max(students , key= lambda item: students[item]['score'])))
Ankit Singh
  • 247
  • 4
  • 14