如何从嵌套数据中获取价值

时间:2019-02-04 05:16:23

标签: python-3.x

我希望从这种复杂的数据中获得最高分,但它显示了错误,也许我在这里做错了。

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

我期望输出:Rohit
  但是这里出现了一个错误cox they're saying item is a string,但就我而言,它也是一个键

2 个答案:

答案 0 :(得分:2)

您可能想要这个-

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

通过lambda,您可以指定密钥。因此,students[item]遍历students,然后遍历get('score')以获得特定条目的分数。

答案 1 :(得分:0)

哦,我明白了!!现在我要从主字典访问元素,然后在元素内部访问

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'])))
相关问题