skip to Main Content

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


  1. Use the del keyword

    >>> test = {"foo": "bar", "foo1": "bar1"}
    >>> del test["foo1"]
    >>> test
    {'foo': 'bar'}
    

    Or try one of these solutions: https://www.geeksforgeeks.org/python-ways-to-remove-a-key-from-dictionary/#

    Login or Signup to reply.
  2. You can do the following:

    new_dict = {}
    key_needed = ["latest.school.city", "latest.school.degree.high" , "latest.student.size", "latest.cost.tution", "school_id"]
    for key in key_needed:
      cur_d = new_dict
      val = data
      levels = key.split('.')[:-1]
      if not levels:
        new_dict[key] = data[key]
        continue
      for k in levels:
        if cur_d.get(k, None) is None:
          cur_d[k] = {}
        cur_d = cur_d[k]
        val = val[k]
      cur_d[k] = val 
    print(json.dumps(
        new_dict,
        indent=4,
        separators=(',', ': ')
    ))
    

    Note: that I assumed each point refer to a level. Also there were problems in your leveling, I corrected them in key_needed.

    Login or Signup to reply.
  3. You can use the library python-box to delete everything you don’t need.

    from box import Box
    
    nested_dict = {
        "latest": {
            "school": {
                "city": 345,
                "degree": {
                    "high": 1
    
                }
            },
            "student": {
                "size": 345
            },
            "cost": {
    
                "tution": [1, 2, 4]
            }
    
        },
        "school_id": 1234
    }
    
    keys_to_delete = [
        "latest.school.degree.high",
        "latest.student.size",
        "latest.student.cost.tution",
        "school_id"
    ]
    
    
    box = Box(nested_dict, box_dots = True)
    
    for key in keys_to_delete:
        try:
            del box[key]
        except:
            # if the key is not existing
            pass
    
    # the new dict
    print(box.to_dict())
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search