0

I'm new to Python and I'm looking to iterate through a dictionary inside a list inside a dictionary (confusing, I know).

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}]}

I need to create a new dictionary of the name of the student and their combined scores (Sally only has one score).

The output would look like:

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

Any help or guidance would be greatly appreciated!

winnieeliz
  • 51
  • 1
  • 7
  • Does this answer your question? [python: iterating through a dictionary with list values](https://stackoverflow.com/questions/18289678/python-iterating-through-a-dictionary-with-list-values) – zetavolt Apr 06 '20 at 02:45
  • Not quite, the issue is that the value is inside a list inside of a dictionary. Unfortunately that solution only works if it were just a list. – winnieeliz Apr 06 '20 at 02:52

2 Answers2

1

Use a dictionary comprehension:

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

Code:

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}
Austin
  • 25,759
  • 4
  • 25
  • 48
0

I try to write a program to solve this case.

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
ifnotak
  • 4,147
  • 3
  • 22
  • 36
McFee
  • 1
  • 2