Vor
Vor

Reputation: 35149

create JSON with multiple dictionaries, Python

I have this code:

>>> import simplejson as json
>>> keys = dict([(x, x**3) for x in xrange(1, 3)])
>>> nums = json.dumps(keys, indent=4)
>>> print nums
{
    "1": 1,
    "2": 8
}

But I want to create a loop to make my output looks like this:

[
    {
        "1": 1,
        "2": 8
    },
    {
        "1": 1,
        "2": 8
    },
    {
        "1": 1,
        "2": 8
    }
]

Upvotes: 6

Views: 30708

Answers (4)

CSe
CSe

Reputation: 281

import simplejson as json

# Create the dictionary
keys = {x: x**3 for x in range(1, 3)}

# Create a list of dictionaries
num_list = [keys for _ in range(3)]

nums = json.dumps(num_list, indent=4)
print(nums)

Upvotes: 0

Grim Reaper
Grim Reaper

Reputation: 1

def sign_up():
    global list
    user_name = input("Enter your User_Name: ")
    password = input("Enter your Password: ")
    user_ID = random.choice(ID)
    dict ={"user_name":user_name,"password":password,"user_ID":user_ID}
    with open("sign_up_details.json", "r") as file:
        read_data = file.read()
        load_data = json.loads(read_data)
        load_data.append(dict)
        new_data = json.dumps(load_data, indent=4)
    with open("", "w") as file:
        file.write(new_data)

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124768

You'd need to create a list, append all the mappings to that before conversion to JSON:

output = []
for something in somethingelse:
    output.append(dict([(x, x**3) for x in xrange(1, 3)])
json.dumps(output)

Upvotes: 10

jterrace
jterrace

Reputation: 67163

Your desired output is not valid JSON. I think what you probably meant to do was to append multiple dictionaries to a list, like this:

>>> import json
>>> multikeys = []
>>> for i in range(3):
...    multikeys.append(dict([(x, x**3) for x in xrange(1, 3)]))
... 
>>> print json.dumps(multikeys, indent=4)
[
    {
        "1": 1, 
        "2": 8
    }, 
    {
        "1": 1, 
        "2": 8
    }, 
    {
        "1": 1, 
        "2": 8
    }
]

Upvotes: 6

Related Questions