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": ""
}
}