0

How can I detect some missing key on location.raw["address"] dictionary. This because, some address doesn't have ['city'] or ['road'] key :(

It gives difficult to me to save the data in the dataframe Python.

This is my code:

from geopy.geocoders import Nominatim

r=[]
h=[] #empty list
c=[]

for i in df['coordinates']:
    loc=geolocator.reverse("%s"%i,timeout=120)
    print(loc)


    if loc.raw["address"]["road"] == None: #i tried use this way, not works
        r.append(" ")
        print("masuk 1")

    else: 
        road=loc.raw["address"]["road"]
        r.append(road)
        print("masuk 2")


    ham=loc.raw["address"]
    name=loc.raw["display_name"]


    h.append(ham)
    c.append(name)

df = pd.DataFrame({'text':text,'city':c,'neighbourhood':h})
Amzar
  • 23
  • 4

1 Answers1

0

You could use in keyword to check if key presented in dict:

a = {1:2, 'x': [3,4]}
print(1 in a) # True
print(2 in a) # False
print('x' in a) # True

Also, dict objects has get method, which returns some value if key is absent:

a.get(1) # 2
a.get(2) # None -- default value
a.get(2, 'n/a') # 'n/a'
mingaleg
  • 2,017
  • 16
  • 28