简体   繁体   English

如何从字典中的元组列表中提取值?

[英]How can I extract values from a list of tuples inside a dictionary?

d={'Test':'Math','results':[{'name':'Paul','score':78},{'name':'Ann','score':87},{'name':'John','score':82}]}

I have this dictionary with a list inside. 我有这本字典,里面有一个清单。 I would like to sum the score: 78+87+82. 我想总结一下分数:78 + 87 + 82。 I've tried some approaches, but I failed. 我尝试了一些方法,但失败了。 Help me, please! 请帮帮我! PS.: I use Python 3.5 PS .:我使用Python 3.5

dct = {'Test':'Math','results':[{'name':'Paul','score':78},{'name':'Ann','score':87},{'name':'John','score':82}]}

print(sum(d["score"] for d in dct["results"]))

dct["results"] is the list of dicts ie: dct["results"]是字典列表,即:

[{'name':'Paul','score':78},{'name':'Ann','score':87},{'name':'John','score':82}], `

d["score"] for d accesses the in each dict using the score key in that list and we just sum all those values we extract. d["score"] for d使用该列表中的score键访问每个字典中的,我们只sum所有提取的值sum

I've got this solution: 我有这个解决方案:

def sumScores(d):
    score=0
    for element in d['results']:
        score += element['score']
    return score

Tip: I see that your question is voted down, it's because that's a simple problem that you CAN solve yourself. 提示:我看到您的问题被否决,因为这是您可以解决自己的一个简单问题。 Try to solve it B4 asking 4 help. 尝试解决它B4寻求4帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM