遍历字典中的列表

时间:2020-04-06 02:44:35

标签: python list dictionary list-comprehension dictionary-comprehension

我是Python的新手,我想遍历字典内列表中的字典(令人困惑,我知道)。

my_dict = {"John": [{"class": "math", "score": 100, "year": 2014}, {"class": "english", "score": 85, "year": 2015}], 
"Timmy": [{"class": "math", "score": 87, "year": 2014}, {"class": "english", "score": 91, "year": 2015}], 
"Sally":[{"class": "math", "score": 95, "year": 2014}]}

我需要创建一个新的字典,其中包含学生的姓名和他们的综合分数(Sally只有一个分数)。

输出如下:

new_dict = {"John": 185, "Timmy": 178, "Sally": 95}

任何帮助或指导将不胜感激!

2 个答案:

答案 0 :(得分:1)

使用字典理解:

{k: sum(x['score'] for x in v) for k, v in my_dict.items()}

代码

my_dict = {"John": [{"class": "math", "score": 100, "year": 2014}, {"class": "english", "score": 85, "year": 2015}], 
"Timmy": [{"class": "math", "score": 87, "year": 2014}, {"class": "english", "score": 91, "year": 2015}], 
"Sally":[{"class": "math", "score": 95, "year": 2014}]}

new_dict = {k: sum(x['score'] for x in v) for k, v in my_dict.items()}
# {'John': 185, 'Timmy': 178, 'Sally': 95}

答案 1 :(得分:0)

我尝试编写一个程序来解决这种情况。

DoSomething