简体   繁体   English

字典中的Python对象和列表

[英]Python Objects and Lists within Dictionary

I'm pretty new to Python, so just working my way through understanding the data sets. 我对Python来说还很陌生,因此请通过了解数据集以自己的方式工作。

I'm having a little trouble producing the JSON output that is required for the API I am working with. 我在生成要使用的API所需的JSON输出时遇到了一些麻烦。

I am using 我在用

import json
json.load(data_file)

Working with Python dictionary and then doing 使用Python字典,然后执行

json.dump(dict, json_data)

My data needs to look like the following when it is output. 输出数据时,我的数据需要如下所示。

    {
  "event":{
    "id":10006,
    "event_name":"My Event Name",
  },
  "sub event":[

  ],
  "attendees":[
    {
      "id":11201,
      "first_name":"Jeff",
      "last_name":"Smith",
    },
    {
      "id":10002,
      "first_name":"Victoria",
      "last_name":"Baker",
    },
  ]
}

I have been able to create the arrays in python and dump to json, but I am having difficulty creating the event "object" in the dictionary. 我已经能够在python中创建数组并将其转储到json,但是在词典中创建事件“对象”时遇到了困难。 I am using the below: 我正在使用以下内容:

attendees = ['attendees']
attendeesdict = {}
attendeesdict['first_name'] = "Jeff"
attendees.append(attendeesdict.copy())

Can anyone help me add the "event" object properly? 谁能帮助我正确添加“事件”对象?

If you want just to statically create a nested dict, you can use a single literal. 如果只想静态创建嵌套字典,则可以使用单个文字。 If you paste the JSON above into python code, you would get a valid dict literal. 如果将上面的JSON粘贴到python代码中,则将获得有效的dict文字。

假设您已将所有值构建在其他位置,现在您将它们放在一起:

result = {'event':event_dict, 'sub event':subevent_list, 'attendees':attendees_list}

In general, going from JSON to dictionary is almost no work because the two are very similar, if not identical: 通常,从JSON到字典几乎是行不通的,因为两者非常相似,甚至不一样:

attendees = [
    {
        "first_name": "Jeff"
        # Add other fields which you need here
    },
    {
        "first_name": "Victoria"
    }    
]

In this instance, attendees is a list of dictionaries. 在这种情况下, attendees是词典列表。 For the event : 对于event

event = {
    "id": 10006,
    "event_name": "My Event Name"
}

Putting it all together: 放在一起:

data = {
    "event": event,
    "sub event": [],
    "attendees": attendees
}

Now, you can convert it to a JSON object, ready to send to your API: 现在,您可以将其转换为JSON对象,准备发送给您的API:

json_object = json.dumps(data)

Construct your dicts and add like below 构建你的dicts并添加如下

    {
      "event":"add your dict"
      "sub event":["add your dict"],
      "attendees":["add your dict"]
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM