Home > Net >  Key error in dictionary when try to add a list element
Key error in dictionary when try to add a list element

Time:04-16

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'

          

CodePudding user response:

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

CodePudding user response:

Here is a way to do what I think you're asking:

my_station_dict = {}

def foo(start_station_name, stop_station_name):
    if start_station_name not in my_station_dict:
        my_station_dict[start_station_name]=[0]*2
    my_station_dict[start_station_name][0]  = 1

    if stop_station_name not in my_station_dict:
        my_station_dict[stop_station_name]=[0]*2
    my_station_dict[stop_station_name][1]  = 1

trips = [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['D', 'B']]
for start, stop in trips:
    foo(start, stop)

print(my_station_dict)

Output:

{'A': [3, 0], 'B': [1, 2], 'C': [0, 2], 'D': [1, 1]}
  • Related