I want to create a nested dictionary from another nested dictionary using python . below is the sample json object which will be loaded as python object , and i’ll need the output as another nested dict.
{
"latest": {
"school": {
"zip": 123,
"city": 345,
"degree": {
"high": 1,
"pre": 45
}
},
"student": {
"size": 345,
"enroll": {
"all": "abc",
"grad": 1099
}
},
"cost": {
"booksupply": 1600,
"tution": [1, 2, 4]
}
},
"school_id": 1234,
"location": {
"lat ": 12.3,
"lon ": 34.23
}
}
— my new dict should look like below ,I am only deleting few nested keys as I do not need them and not changing the level or reformatting the keys as such .
for example : I deleted the key latest.school.zip latest.student.enroll latest.school.zip latest.cost.booksupply location
{
"latest": {
"school": {
"city": 345,
"degree": {
"high": 1
}
},
"student": {
"size": 345
},
"cost": {
"tution": [1, 2, 4]
}
},
"school_id": 1234
}
— I am new to python hence not sure what is the best way to create the new dictionary assuming that there are 4000 keys (nested )in this dict which needs to be deleted and only 50 keys will remain in this dict object and I do not want to type all the names ,it is easier to give a list of keys which I want to keep and create a dictionary using this list of keys .
for example; (the below is not correct syntax and I am not sure what the correct syntax is for nested keys ).
key_needed = [latest.school.city.degree.high , latest.student.size, latest.student.cost.tution, school_id ]
— reading the json file and creating a new dict.
f = open (json_file_path) data = json.load(f) new_dict = {x:data{x} for x in key_needed}
I am not sure how to create the list of key_needed when the keys are nested . please suggest any other ways to create the new dict if above is not ideal approach.
3
Answers
Use the
del
keywordOr try one of these solutions: https://www.geeksforgeeks.org/python-ways-to-remove-a-key-from-dictionary/#
You can do the following:
Note: that I assumed each point refer to a level. Also there were problems in your leveling, I corrected them in
key_needed
.You can use the library
python-box
to delete everything you don’t need.