Search code examples
pythonlistdictionarylist-comprehensiondictionary-comprehension

Iterate over list inside dictionary


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!


Solution

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