Search code examples
pythonjsondictionary

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
    }
]

Solution

  • 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)