Ankit Singh
Ankit Singh

Reputation: 247

How to get value from nested data

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

Upvotes: 1

Views: 48

Answers (2)

Ankit Singh
Ankit Singh

Reputation: 247

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

Upvotes: 0

Arnab Roy
Arnab Roy

Reputation: 619

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.

Upvotes: 3

Related Questions