0

I would like to tranform an array to on object .

I have an array : ['BROOKLYN','STATEN ISLAND','OZONE PARK','SOUTH OZONE PARK', 'JAMAICA','OZONE PARK']

I am going to transofrm it to json object adding ":red" prefix .

colormap = {'NEW YORK': 'red', 'BROOKLYN': 'red', 'STATEN ISLAND': 'red', 'OZONE PARK':'red','SOUTH OZONE PARK':'red', 'JAMAICA':'red','OZONE PARK': 'red'} 

How can I do that ?

1
  • 3
    It looks like you want to convert a list to a dictionary. How does this have anything to do with JSON? Commented Nov 27, 2013 at 4:57

3 Answers 3

2

As I understand, you want to create a dict from your list. If so, you can do it like this:

colormap = {x:'red' for x in myList}

Afterwards, you can save it in json format using json module (please see a relevant question Storing Python dictionaries and documentation).

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

2 Comments

Thanks ! What is the best way to save it to json object (.to_JSON() )
@user3001937 Please check out the edit for json info (has been asked a few times before - you can search other similar questions).
0
  1. You can use fromkeys method in the dictionary, like this

    print {}.fromkeys(myArray, "set")
    
  2. Or you can use zip like this

    print dict(zip(myArray, ["set"] * len(myArray)))
    

Output

{'OZONE PARK': 'set', 'BROOKLYN': 'set', 'STATEN ISLAND': 'set', 'SOUTH OZONE PARK': 'set', 'JAMAICA': 'set'}

2 Comments

dict.fromkeys seems like it would be the right way. ({}.fromkeys doesn’t have a lot of meaning.) But why bother with zip at all?
dict.fromkeys is ideal since the value is immutable. The version with zip...why would you ruin a good answer with that?
0
import json

array = ["test", "test1", "test2"]

colors = {item: "red" for item in array}

json_str_colors = json.dumps(colors)

print(repr(json_str_colors))

Comments

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.