遍历字典中的列表
Iterate over list inside dictionary
我是 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}
如有任何帮助或指导,我们将不胜感激!
使用字典理解:
{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}
我试着写一个程序来解决这个问题。
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
我是 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}
如有任何帮助或指导,我们将不胜感激!
使用字典理解:
{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}
我试着写一个程序来解决这个问题。
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