0

I'm using the OpenStreetMap API to extract some data about a particular area using the code below:

import requests
import json

overpass_url = "http://overpass-api.de/api/interpreter"
overpass_query = """
[out:json];
area["ISO3166-1"="DE"][admin_level=2];
(node["amenity"="place_of_worship"](area);
 way["amenity"="place_of_worship"](area);
 rel["amenity"="place_of_worship"](area);
);
out center;
"""
response = requests.get(overpass_url, 
                        params={'data': overpass_query})
data = response.json()

I then try to print out all the 'names' from the above using the following code:

for tags in data['elements']:
    print(tags['tags']['name'])

This works fine for the first 12 or so results, but hits an issue when it comes across a result without a 'name' value within the 'tags' dictionary:

Epiphanias Kirche
Kirche St. Bilhildis
Kleine Kreuzkirche
Marienkapelle
Kath. Kirche Heilige Familie
St. Cyriakus
Friedhofskapelle
Ev. Hoffnungsgemeinde / Philippuszentrum
Petrikirche
Sankt Paulus
Kapelle Höver
Pfarrkirche St. Laurentius

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-81-5758361aa6f2> in <module>()
      1 for tags in data['elements']:
----> 2     print(tags['tags']['name'])
      3 
      4 #error occurs because not all have name tags

KeyError: 'name'

Is there a way I could skip any missing 'name' values and just keep on parsing?

1 Answer 1

1

Try using dict.get

Ex:

for tags in data['elements']:
    print(tags['tags'].get('name'))

you can also set a default value. Ex: print(tags['tags'].get('name', "EMPTY"))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.