1

I have the list below:

rainbow = ['green', 'red', 'blue', 'yellow' ,'orange']

and I would like the output to be a JSON object like so:

{
  "rainbow":[
    {
        "color": "green"
    },
    {
        "color": "red"
    },
    {
        "color": "blue"
    },
    {
        "color": "yellow"
    }
    {
        "color": "orange"
    }
]}

any ideas? I've tried a couple of things and been struggling to find a solution.

import json
import itertools

rainbow = ['green', 'red', 'blue', 'yellow' ,'orange']

d = dict((k,'color') for k in rainbow)

skittles = json.dumps(d)

print skittles

{"blue": "color", "orange": "color", "green": "color", "yellow": "color", "red": "color"}
2
  • 3
    Maybe you're close to the solution? Post your code. Commented Dec 7, 2016 at 14:32
  • whoops, my bad...just added Commented Dec 7, 2016 at 14:38

2 Answers 2

2

Your solution creates a flat dictionary with wrong key-value order. You should try something like:

{'rainbow': [{'color': color} for color in rainbow]}

This creates a 'rainbow' key, with a list of dictionaries as its value (created using list comprehension).

Sign up to request clarification or add additional context in comments.

Comments

1

You can do this something like that:

import json
json.dumps({"rainbow": [{"color": color} for color in rainbow]})

1 Comment

Marcin, thank you for assisting as well. I went with Maroun's answer above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.