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 ?

user3001937
  • 2,005
  • 4
  • 19
  • 23

3 Answers3

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

Community
  • 1
  • 1
sashkello
  • 17,306
  • 24
  • 81
  • 109
1
  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'}
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 2
    `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? – Ry- Nov 27 '13 at 05:06
  • 1
    `dict.fromkeys` is ideal since the value is immutable. The version with zip...why would you ruin a good answer with that? – John La Rooy Nov 27 '13 at 05:14
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))
Tim Wilder
  • 1,607
  • 1
  • 18
  • 26