Retrieve specific keys and values from a nested dictionary and assign them into a new dictionary in python 3.X

I am currently new to python and my objective currently is to retrieve specific keys and values from a JSON data that I have converted into a dictionary format from a RESTful API and assign them to a new dictionary so that I can display them in a HTML template in flask in table form.

Below is the JSON data mentioned and I want to extract only the "dateRented", "username" in "user", "vehicleModel" and "vehicleBrand" in "vehicle".

[
  {
    "dateRented": "2020-05-22", 
    "recordsID": 1, 
    "user": {
      "firstname": "Ching", 
      "imageName": "croppedCY", 
      "password": "gAAAAABeuQsw-u6FTh3_2VZiXZGTuiJEhbBuLB4FwyPj5xKb33tkJ7HTH7YvZTWxi0MJ3UKqLQAd6LHoXgCahB1gC5qJo9wSHw==", 
      "surname": "Loo", 
      "userID": 10, 
      "username": "CY"
    }, 
    "vehicle": {
      "colour": "White", 
      "cost": 15, 
      "latitude": null, 
      "longitude": null, 
      "rentalStatus": "True", 
      "seats": 4, 
      "user": null, 
      "vehicleBrand": "Honda", 
      "vehicleID": 4, 
      "vehicleModel": "CRZ"
    }
  }
]

2 answers

  • answered 2020-06-02 10:41 Chris S

    let's say your dictionary is called "my_data"

    and you have a new dictionary called "new_dict"

    You would do something like this:

    new_dict["dateRented"] = my_data[0]["dateRented"]
    new_dict["username"] = my_data[0]["user"]["username"]
    new_dict["vehicleModel"] = my_data[0]["vehicle"]["vehicleModel"
    new_dict["vehicleBrand"] = my_data[0]["vehicle"]["vehicleBrand"]
    

  • answered 2020-06-02 10:41 deadshot

    Data in the json file have object inside the list you can use loop to iterate through each object in the list then you can easily get the values using dict.get() method it will return the value if the given key exist otherwise it will return default value.

    import json
    
    with open('data.json') as fp:
        data = json.loads(fp.read())
    
    for x in data:
        date_rented = x['dateRented']
        user_name = x['user'].get('username', '')
        vehicle_brand = x['vehicle'].get('vehicleBrand', '')
        vehicle_model = x['vehicle'].get('vehicleModel', '')
        print(date_rented, user_name, vehicle_brand, vehicle_model)
        #2020-05-22 CY Honda CRZ