Conditional if statement within a for loop to print out values from a dictionary returns nothing

Question:

Here is how I created my dictionary

station_dict = {}
for station in metro['start_station'].unique():
    lat_list = metro[metro['start_station'] == station]['start_lat'].unique()
    lon_list = metro[metro['start_station'] == station]['start_lon'].unique()
    if len(lat_list) == 1 and len(lon_list) == 1:
        station_dict[station] = {'lat': lat_list[0], 'lon': lon_list[0]}
        
metro.drop(columns=['start_lat', 'start_lon', 'end_lat', 'end_lon'], inplace=True)

Then I accessed a single key in the dictionary

print(station_dict['4285'])

which gave an output: {‘lat’: ‘nan’, ‘lon’: ‘nan’}

However, if I then try to access values in a for loop like so

for key, value in station_dict.items():
    if value == 'nan':
        print(key)

It returns nothing and I get no errors

I have tried altering the loop and looking at other posts with similar issues but nothing really helped, I am also working in jupyter notebook so note sure if that could affect this?

I am expecting the for loop to print out a few keys where the lat and lon are equal to ‘nan’.

Asked By: Amy Gregory

||

Answers:

for key, value in station_dict.items():

Should be

for key, value in station_dict.items():
    if value and isinstance(value, dict):
        for inside_key, v in value:
            if v == 'nan':
                # do something

You have missed that, the value is actually a dictionary itself. You can do further checks depending on your data (whether value is indeed dictionary and similar checks).

Answered By: user2736738
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.