Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Key error in dictionary when try to add a list element

I’m trying to add a count in a dictionary that has this final restructure: {'stationA':[2,3], 'stationB':[1,0]}

 if start_station_name not in my_station_dict:
                my_station_dict["station_name"]=start_station_name
                my_station_dict[start_station_name][0]=0
 my_station_dict[start_station_name][0] += 1

 if stop_station_name not in my_station_dict:
            my_station_dict["station_name"] = stop_station_name
            my_station_dict[stop_station_name][1] = 0
 my_station_dict[stop_station_name][1] += 1

But I get

my_station_dict[start_station_name][0]=0
KeyError: 'N 6 St & Bedford Ave'

          

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

my_station_dict["station_name"]=start_station_name

You are adding "station_name" as a key in your dict, but then trying to access it using the key start_station_name. To be clear, your code is creating this:

{'station_name': 'N 6 St & Bedford Ave'}

When you really want this:

{'N 6 St & Bedford Ave': [0, 0]}

It’s a simple update:

if start_station_name not in my_station_dict:
    my_station_dict[start_station_name] = [0, 0]
my_station_dict[start_station_name][0] += 1

if stop_station_name not in my_station_dict:
    my_station_dict[stop_station_name] = [0, 0]
my_station_dict[stop_station_name][1] += 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading