Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在字典内的列表上迭代_Python_List_Dictionary_List Comprehension_Dictionary Comprehension - Fatal编程技术网

Python 在字典内的列表上迭代

Python 在字典内的列表上迭代,python,list,dictionary,list-comprehension,dictionary-comprehension,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": 201

我是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}]}
我需要建立一个新的学生名字字典,他们的总分萨利只有一分

输出如下所示:

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

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

使用字典理解:

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


我试图写一个程序来解决这个问题

score_dict = {}
for name in my_dict:
    score_dict[name] = 0
    class_items = my_dict[name]
    for class_item in class_items:
        score_dict[name] += class_item['score']

print score_dict

这回答了你的问题吗?不完全是这样,问题是该值位于字典中的列表中。不幸的是,只有当它只是一个列表时,这个解决方案才有效。
score_dict = {}
for name in my_dict:
    score_dict[name] = 0
    class_items = my_dict[name]
    for class_item in class_items:
        score_dict[name] += class_item['score']

print score_dict