如何用Python为GeoJSON中的每个字典添加递增RANK字段?
为GeoJSON的每个Feature添加递增RANK字段的Python实现
问题描述
我有一个包含数百行类似结构的GeoJSON文件,已通过代码XYZ=json.load(open("countries.geo.json",'r'))加载。希望为每个Feature字典添加"RANK"字段,并为其分配从1开始的递增数值。
现有输入示例(单个Feature结构):
{'type': 'Feature', 'id': 'BEL', 'properties': {'name': 'Belgium'}, 'geometry': {'type': 'Polygon', 'coordinates': [[[3.314971, 51.345781], [4.047071, 51.267259], [3.314971, 51.345781]]]}} {'type': 'Feature', 'id': 'BLZ', 'properties': {'name': 'Belize'}, 'geometry': {'type': 'Polygon', 'coordinates': [[[-89.14308, 17.808319], [-89.150909, 17.955468], [-89.14308, 17.808319]]]}}
期望输出示例:
{'type': 'Feature', 'id': 'BEL', 'properties': {'name': 'Belgium'}, 'RANK':'1', 'geometry': {'type': 'Polygon', 'coordinates': [[[3.314971, 51.345781], [4.047071, 51.267259], [3.314971, 51.345781]]]}} {'type': 'Feature', 'id': 'BLZ', 'properties': {'name': 'Belize'}, 'RANK':'2', 'geometry': {'type': 'Polygon', 'coordinates': [[[-89.14308, 17.808319], [-89.150909, 17.955468], [-89.14308, 17.808319]]]}}
解决方案
GeoJSON加载后是一个字典,其中features键对应的值是所有Feature对象组成的列表。我们可以遍历这个列表,用enumerate函数获取从1开始的索引,给每个Feature添加RANK字段即可。
完整代码示例
import json # 加载GeoJSON文件 XYZ = json.load(open("countries.geo.json", 'r')) # 遍历features列表,添加RANK字段 for rank, feature in enumerate(XYZ['features'], start=1): feature['RANK'] = str(rank) # 如果需要数值类型,去掉str() # 可选:将修改后的内容写回文件 with open("countries_with_rank.geo.json", 'w') as f: json.dump(XYZ, f, indent=2)
代码说明
enumerate(XYZ['features'], start=1):遍历features列表时,从1开始计数,避免默认从0开始的索引。feature['RANK'] = str(rank):按照示例要求将RANK设为字符串类型,如果需要数值类型,直接赋值rank即可。- 最后可选将修改后的GeoJSON写回新文件,保留原文件不受影响。
内容的提问来源于stack exchange,提问作者coderunner84
相关产品推荐
相关产品推荐

