为了账号安全,请及时绑定邮箱和手机立即绑定

从嵌套字典中检索特定的键和值,并将它们分配到 python 3.X 中的新字典中

从嵌套字典中检索特定的键和值,并将它们分配到 python 3.X 中的新字典中

慕姐8265434 2022-12-20 14:33:14
我目前是 python 的新手,我目前的目标是从我已从 RESTful API 转换为字典格式的 JSON 数据中检索特定的键和值,并将它们分配给新字典,以便我可以在 HTML 模板中显示它们在表格形式的烧瓶中。下面是提到的 JSON 数据,我只想提取“用户”中的“dateRented”、“用户名”、“车辆”中的“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"    }  }]
查看完整描述

2 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

json 文件中的数据在列表中有对象,您可以使用循环遍历列表中的每个对象,然后您可以使用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


查看完整回答
反对 回复 2022-12-20
?
GCT1015

TA贡献1827条经验 获得超4个赞

假设您的字典名为“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"]


查看完整回答
反对 回复 2022-12-20
  • 2 回答
  • 0 关注
  • 96 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信