0

I have a Python script that reads a json file and removes specific keys based on different requirements. Currently I want to remove 2 keys "country" and "region". Using data.pop('country') is fine but I can't seem to remove the key "region" nested inside "extra"

{
    "organization": "GeeksForGeeks",
    "city": "Noida",
    "country": "India",
    "extra": {
        "region": "US",
        "lat": "",
        "long": ""
    }
}

This is what I have tried so far. The error RuntimeError: dictionary changed size during iteration keeps popping up all the time.

with open("C:\\Users\\sam\\Downloads\\test\\Sample.json") as data_file:
    data = json.load(data_file)
    data.pop('country')
    print(data)
    for key in data['extra'].keys():
        print(key)
        if key == 'region':
            data['extra'].pop(key, None)
    print(data)

Desired output:

{
    "organization": "GeeksForGeeks",
    "city": "Noida",
    "extra": {
        "lat": "",
        "long": ""
    }
}
B Lee
  • 13
  • 2
  • The dictionary can **only possibly have one** `region` key (dictionaries, by construction, cannot duplicate keys), so there is **no reason to iterate** the dictionary in order to remove a specific key. I gave duplicate links both for how to remove a single key, and to explain how the iteration goes wrong. – Karl Knechtel Mar 28 '23 at 23:10

1 Answers1

0

It's not clear why you're bothering to iterate through extra; you could just do something like:

import json

with open("data.json") as data_file:
    data = json.load(data_file)
    if 'country' in data:
        del data['country']
    if 'region' in data['extra']:
        del data['extra']['region']

    print(json.dumps(data, indent=2))

Which results in:

{
  "organization": "GeeksForGeeks",
  "city": "Noida",
  "extra": {
    "lat": "",
    "long": ""
  }
}
larsks
  • 277,717
  • 41
  • 399
  • 399