Python字典更新:将多组数据合并到单个GeoJSON Feature中
合并GeoJSON的Feature对象,将id信息整合到主Feature中
核心思路
先从features数组中区分出带几何信息的主Feature,再将其余仅含id信息的Feature的属性全部合并到主Feature的properties字段,最后重构features数组只保留合并后的主Feature。
代码实现示例
假设你现有代码生成的GeoJSON数据存储在geojson_data字典中,修改逻辑如下:
import json # 假设这是你现有代码生成的GeoJSON数据 geojson_data = { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": {"type": "Point", "coordinates": [100.0, 0.0]}, "properties": {"name": "Main Location"} }, {"type": "Feature", "properties": {"id_1": "LOC-001"}}, {"type": "Feature", "properties": {"id_2": "LOC-002"}} ] } # 1. 分离主Feature与id信息Feature main_feature = None id_features = [] for feature in geojson_data["features"]: # 判定主Feature:根据实际场景调整条件,这里以存在非空geometry为例 if "geometry" in feature and feature["geometry"] is not None: main_feature = feature.copy() # 确保properties字段存在,避免KeyError main_feature.setdefault("properties", {}) else: id_features.append(feature) # 2. 合并所有id属性到主Feature for id_feature in id_features: if "properties" in id_feature: # 合并字典,重复键会被后续值覆盖,按需调整逻辑 main_feature["properties"].update(id_feature["properties"]) # 3. 重构GeoJSON的features数组 geojson_data["features"] = [main_feature] # 输出结果 print(json.dumps(geojson_data, indent=2))
自定义调整说明
- 主Feature判定条件:如果你的主Feature不是靠
geometry区分,而是有特定标识(比如properties里有is_main字段),可以修改判定逻辑为if feature["properties"].get("is_main")。 - 重复键处理:如果存在属性键重复的情况,不想覆盖而是保留所有值,可以替换合并逻辑为:
for key, value in id_feature["properties"].items(): if key in main_feature["properties"]: # 转成列表存储多值 if not isinstance(main_feature["properties"][key], list): main_feature["properties"][key] = [main_feature["properties"][key]] main_feature["properties"][key].append(value) else: main_feature["properties"][key] = value - 批量文件处理:如果是从多文件提取数据时实时合并,可以在读取每个文件的数据时,直接将id属性追加到主Feature的
properties中,无需先生成多个Feature再合并。
内容的提问来源于stack exchange,提问作者Zeylon
相关产品推荐
相关产品推荐

