else子句中的“删除”更改通过JSON dict循环的结果

时间:2019-05-08 13:17:00

标签: python json dictionary

我正在遍历从json文件创建的字典,该字典工作正常,但是一旦我删除了else子句中的某些条目,结果就会更改(通常会打印35个nuts_id,但带有{{1 }}在remove中只打印了32个,因此删除似乎影响了迭代,但是为什么呢?密钥应该安全吗?如何在不丢失数据的情况下适当地做到这一点?

else

2 个答案:

答案 0 :(得分:5)

迭代对象时删除项目不是一个好习惯。相反,您可以尝试过滤掉所需的元素。

例如:

import json

with open("test.json") as json_file:
    json_data = json.load(json_file)

json_data_features = [g for g in json_data["features"] if g["properties"]["CNTR_CODE"] == "AT"]  #Filter other country codes.  
json_data["features"] = json_data_features

for g in json_data["features"]:
    poly = g["geometry"]
    cntr_code = g["properties"]["CNTR_CODE"]
    nuts_id = g["properties"]["NUTS_ID"]
    name = g["properties"]["NUTS_NAME"]
    # do plotting etc

# do something else with the json_data

答案 1 :(得分:1)

永远记住基本规则,永远不要修改要迭代的对象

您可以复制字典,然后使用copy.copy

对其进行迭代。
import json
import copy
with open("test.json") as json_file:
    json_data = json.load(json_file)

#Take copy of json_data 
json_data_copy = json_data['features'].copy()

#Iterate on the copy
for g in json_data_copy:
    poly = g["geometry"]
    cntr_code = g["properties"]["CNTR_CODE"]
    nuts_id = g["properties"]["NUTS_ID"]
    name = g["properties"]["NUTS_NAME"]
    if cntr_code == "AT":
        print(nuts_id)
        # do plotting etc
    else: # delete it if it is not part a specific country
        json_data["features"].remove(g)  # line in question