Python如何展开GeoJSON中嵌套的tags字典并追加到新列表
实现代码
你可以直接在循环内通过字典的pop和update方法完成展开操作,有两种常用写法:
写法1:直接修改原geo对象(最简)
filtered = [] for geo in data['features']: # 取出tags字典并删除properties中的tags键,再将tags内容合并到properties geo['properties'].update(geo['properties'].pop('tags')) filtered.append(geo)
写法2:不修改原始加载的geojson数据(更安全)
如果你需要保留原始的data数据不变,可以先做拷贝再修改:
import copy filtered = [] for geo in data['features']: # 深拷贝当前geo对象,避免修改原数据 new_geo = copy.deepcopy(geo) new_geo['properties'].update(new_geo['properties'].pop('tags')) filtered.append(new_geo)
逻辑说明
dict.pop('tags')会同时完成两个操作:返回properties下tags对应的字典,同时删除properties里的tags键dict.update()会将tags字典里的所有键值对直接合并到properties字典中,最终得到你需要的结构
内容的提问来源于stack exchange,提问作者bvboisseree
相关产品推荐
相关产品推荐

