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": ""
    }
}
1
  • 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. Commented Mar 28, 2023 at 23:10

1 Answer 1

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": ""
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.