簡體   English   中英

從嵌套字典中檢索特定鍵和值並將它們分配到 python 3.X 中的新字典中

[英]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以表格形式在 flask 中。

下面是提到的 JSON 數據,我只想提取“用戶”中的“dateRented”、“username”、“vehicle”中的“vehicleModel”和“vehicleBrand”。

[
  {
    "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"
    }
  }
]

假設您的字典名為“my_data”

你有一本名為“new_dict”的新字典

你會做這樣的事情:

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"]

json 文件中的數據在列表中有 object 您可以使用循環遍歷列表中的每個 object 然后您可以使用dict.get()輕松獲取值默認值。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM