Search code examples
pythonlistdictionarykeyerror

Dictionary list raised a key error in Python


I have a list of dictionary, and I would like to count the values for keys of "increasing" and "decreasing" respectively. My script returned a key error that might because not all dictionaries have "increasing" and "decreasing" both. But I have no idea how to fix it. As a Python beginner, any help would be appreciated.

list_of_dicts = [{"decreasing": 1}, {"increasing": 4}, {"decreasing": 1}, {"increasing": 3},{"decreasing": 1},
             {"increasing": 1}]

values1 = [a_dict["decreasing"] for a_dict in list_of_dicts]
values2 = [a_dict["increasing"] for a_dict in list_of_dicts]

print(values1)
print(values2)

The expected result is:

[1,1,1]
[4,3,1]

Solution

  • Add an if in the list comprehension, that'll keep the good ones

    values1 = [a_dict["decreasing"] for a_dict in list_of_dicts if "decreasing" in a_dict]
    values2 = [a_dict["increasing"] for a_dict in list_of_dicts if "increasing" in a_dict]
    
    print(values1)  # [1, 1, 1, 1, 2, 1, 2]
    print(values2)  # [4, 3, 1, 5, 11, 1, 4]