大家好,我正在尋求幫助,試圖將多個嵌套的 dicts 展平并將它們附加到一個新串列中。我有多個字典,從這樣的 geojson 檔案加載:
data = json.load(open("xy.geojson"))
它們的結構都是這樣的:
{'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]]}}
現在我想壓平字典的“標簽”部分,所以我得到:
{'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]]}}
到目前為止,我所做的是設定一個新串列并啟動一個 for 回圈:
filtered = []
for geo in data['features']:
但是如何在回圈中展平geo['properties']['tags']并將每個 dict 的結果附加到過濾器中?非常感謝大家,感謝您的幫助!克萊門斯
uj5u.com熱心網友回復:
可能有更好的方法,但這似乎有效:
filtered = []
for geo in data["features"]:
updated = dict(**geo)
updated["properties"] = geo["properties"]["tags"]
filtered.append(updated)
print(filtered)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366615.html
