简体   繁体   中英

Getting specific information from raw information in python

Firstly sorry for how badly my question is phrased but I am not 100% sure how to explain what I am looking for. I am using the geopy package in python.

Basically I use the following code:

geolocator = Nominatim()
location = geolocator.reverse("{}, {}".format(lat, lon))
print(location.address)
print((location.latitude, location.longitude))
print(location.raw)

An example of the output it gives me is:

Coastal Track, Totaranui, Tasman, New Zealand/Aotearoa

(-40.8274559, 173.0053319)

{u'display_name': u'Coastal Track, Totaranui, Tasman, New Zealand/Aotearoa', u'place_id': u'93390086', u'lon': u'173.0053319', u'osm_type': u'way', u'licence': u'Data \xa9 OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright', u'osm_id': u'149082205', u'lat': u'-40.8274559', u'address': {u'path': u'Coastal Track', u'state': u'Tasman', u'country': u'New Zealand/Aotearoa', u'country_code': u'nz', u'hamlet': u'Totaranui'}}

What I want to do is take things like the osm_id, osm_type etc and create a variable for them. I tried something like location.raw.attrib['osm_type'] but that does not work. I am new to python so would really appreciate any help and I hope I was clear enough with what I am asking, thanks!

What you're looking for is calling key-value pairs from dictionaries. So to get what you want, osm_id and osm_type in variables, you would do this:

osmid = location['osm_id']

You call the part of the dictionary you want with the name of the dictionary (location) and the name of the key you want to get the value of. Then, we store it in osmid .

n1c9 answer will throw Key Error if the key doesnt exist. Please use:

dict = location.raw
osmid = dict.get('osm_id', 'default_value_if_null_here')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM