Home > front end >  Python: Flatten multiple nested dict and append
Python: Flatten multiple nested dict and append

Time:11-26

I Hello all, I am looking for help in trying to flatten multiple nested dicts and append them to a new list. I have multiple dicts, loaded from a geojson-File like that:

data = json.load(open("xy.geojson"))

They are all structured like that:

{'type': 'Feature', 'properties': {'tags': {'highway': 'cycleway', 'lit': 'yes', 'source': 'survey 08.2018 and Esri', 'surface': 'paving_stones', 'traffic_sign': 'DE:237 Radweg'}}, 'geometry': {'type': 'LineString', 'coordinates': [[6.7976974, 51.1935231], [6.7977131, 51.1935542], [6.7977735, 51.1935719], [6.7978679, 51.193578], [6.798005, 51.1936044], [6.7982118, 51.1936419], [6.7983474, 51.1936511], [6.7984899, 51.1936365], [6.7985761, 51.193623], [6.7986739, 51.1936186], [6.7987574, 51.1936188], [6.7988269, 51.1936342], [6.7988893, 51.1936529], [6.7989378, 51.1936778], [6.7990085, 51.1937739]]}}

Now I'd like to flatten the 'tags'-part of the dict, so I get:

{'type': 'Feature', 'properties': {'highway': 'cycleway', 'lit': 'yes', 'source': 'survey 08.2018 and Esri', 'surface': 'paving_stones', 'traffic_sign': 'DE:237 Radweg'}, 'geometry': {'type': 'LineString', 'coordinates': [[6.7976974, 51.1935231], [6.7977131, 51.1935542], [6.7977735, 51.1935719], [6.7978679, 51.193578], [6.798005, 51.1936044], [6.7982118, 51.1936419], [6.7983474, 51.1936511], [6.7984899, 51.1936365], [6.7985761, 51.193623], [6.7986739, 51.1936186], [6.7987574, 51.1936188], [6.7988269, 51.1936342], [6.7988893, 51.1936529], [6.7989378, 51.1936778], [6.7990085, 51.1937739]]}}

What I've done so far is setting up a new list and starting a for-loop:

filtered = []
for geo in data['features']:

But how can I flatten geo['properties']['tags'] within loop and append the result for each dict to filtered? Thank you all so much, appreciate your help! Clemens

CodePudding user response:

There's probably a better way, but this seems to work:

filtered = []
for geo in data["features"]:
    updated = dict(**geo)
    updated["properties"] = geo["properties"]["tags"]
    filtered.append(updated)

print(filtered)
  • Related