2 回答

TA貢獻1804條經驗 獲得超8個贊
您需要在遍歷時進行枚舉data['features'],以便可以分配回正確的值
data['features'][0]僅分配給ph列表索引 0。
with open('filepath', 'r+') as f:
data = json.load(f)
for i, feature in enumerate(data['features']): # enumerate while iterating
print(feature['properties'])
if feature['properties']["ID"] == 2:
data['features'][i]['properties']["pH"]=10 # assign back to the correct index location
f.seek(0)
json.dump(data, f)
f.truncate()

TA貢獻1887條經驗 獲得超5個贊
data['features'][0]
由 [0] 索引,因此修改data["features"]. 您希望它根據評估為True您的條件的索引進行修改feature['properties']["ID"] == 2。
嘗試
for index, feature in enumerate(data['features']):
...
if feature['properties']["ID"] == 2:
data['features'][index]['properties']["pH"] = 10
...
添加回答
舉報