user3822146
user3822146

Reputation: 114

Insert JSON in Array Python

I have a dict created in a for loop in Python dict = {year:{month:{day:[title]}}} where year, month, day, and title are all variables. I then use data = json.dumps(dict) which works perfectly. But if the day is the same, I'd like it to add another [title] aspect to the array, so it would be

for title in x:
    dict = {year:{month:{day:[title]}}}
    data = json.dumps(dict)
if day==day:
    //insert another [title] right next to [title]

I've tried using append, update, and insert, but none of them work.

How would I go about doing this?

Upvotes: 1

Views: 336

Answers (1)

Casey Falk
Casey Falk

Reputation: 2667

Note that as user2357112 mentioned, you are creating a Python dict -- not a Python list (aka a JSON "array"). Thus, when you say "[title] right next to [title]" there is a bit of confusion. Dicts do not use the order you are expecting (they use a hash-ordering).

That, and you are attempting to add a field after you've dumped the JSON to a string. You should do that before you dump it. More so, you're throwing away both your dict and data variables every loop. As written, your code will only have access to the variables in the last iteration of the loop.

And another important note: don't overload dict. Rename your variable to something else.

Also, your line day==day will always return True...

Here is what I think you are trying to do: you are creating a "calendar" of sorts that is organized into years, then months, then days. Each day has a list of "titles."

# Variables I'm assuming exist:
# `title`, `year`, `month`, `day`, `someOtherDay`, `titles`, `someOtherTitle`

myDict = {}
for title in titles: #Renamed `x` to `titles` for clarity.
    # Make sure myDict has the necessary keys.
    if not myDict[year]:
        myDict[year] = {}
    if not myDict[year][month]: 
        myDict[year][month] = {}

    # Set the day to be a list with a single `title` (and possibly two).
    myDict[year][month][day] = [title]
    if day==someOtherDay:
        myDict[year][month][day].append(someotherTitle)

    # And FINALLY dump the result to a string.
    data = json.dumps(myDict) 

Upvotes: 3

Related Questions