CareFree
CareFree

Reputation: 311

Python Objects and Lists within Dictionary

I'm pretty new to Python, so just working my way through understanding the data sets.

I'm having a little trouble producing the JSON output that is required for the API I am working with.

I am using

import json
json.load(data_file)

Working with Python dictionary and then doing

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. 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?

Upvotes: 0

Views: 101

Answers (4)

Hai Vu
Hai Vu

Reputation: 40688

In general, going from JSON to dictionary is almost no work because the two are very similar, if not identical:

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

In this instance, attendees is a list of dictionaries. For the 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_object = json.dumps(data)

Upvotes: 1

zefciu
zefciu

Reputation: 2046

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.

Upvotes: 1

Januka samaranyake
Januka samaranyake

Reputation: 2597

Construct your dicts and add like below

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

Upvotes: 0

Patrick Haugh
Patrick Haugh

Reputation: 60944

Assuming you have built all the values elsewhere and now you're just putting them together:

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

Upvotes: 1

Related Questions