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

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

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

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

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’.

>Solution :

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).

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