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

lor*_*rdy 0 python json dictionary

我遍历从JSON文件,它工作正常,但只要我删除一些条目中创建一个字典else子句结果的变化(通常它打印35个nuts_ids但随着removeelse只有32个被打印出来。这样看来,移除会影响迭代,但是为什么呢?密钥应该是安全的?如何在不丢失数据的情况下适当地做到这一点?

import json

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

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"]
    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

# do something else with the json_data
Run Code Online (Sandbox Code Playgroud)

Rak*_*esh 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
Run Code Online (Sandbox Code Playgroud)