How to convert array to dict in python

Now I want to convert the array to dict like so:

dict = {'item0': arr[0], 'item1': arr[1], 'item2': arr[2]...}

      

How can I solve this problem elegantly in python?

+3


source to share


6 answers


You can use enumerate

dictionary comprehension as well:



>>> arr = ["aa", "bb", "cc"]
>>> {'item{}'.format(i): x for i,x in enumerate(arr)}
{'item2': 'cc', 'item0': 'aa', 'item1': 'bb'}

      

+11


source


Suppose we have a list int

s:

We can use dict comprehension



>>> l = [3, 2, 4, 5, 7, 9, 0, 9]
>>> d = {"item" + str(k): l[k] for k in range(len(l))}
>>> d
{'item5': 9, 'item4': 7, 'item7': 9, 'item6': 0, 'item1': 2, 'item0': 3, 'item3': 5, 'item2': 4}

      

+2


source


simpleArray = [ 2, 54, 32 ]
simpleDict = dict()
for index,item in enumerate(simpleArray):
    simpleDict["item{0}".format(index)] = item

print(simpleDict)

      

Okay, first line. Input, second line is an empty dictionary. We'll fill it out on the fly.

Now we need to iterate, but normal iteration, like in C, is considered not Pythonic. The enumeration will give the index and element that we need from the array. See This: Python Loop Index Access for Loops.

So, at each iteration, we will get an element from the array and insert it into the dictionary using the key from the parenthesized string. I am using the format as using% is not recommended. See here: Python String Formatting:% vs. .format .

Finally, we will print. Uses the print function as a function for greater compatibility.

+1


source


you can use dictionary comprehension eg.

>>> x = [1,2,3]
>>> {'item'+str(i):v for i, v in enumerate(x)}
>>> {'item2': 3, 'item0': 1, 'item1': 2}

      

+1


source


Using a dictionary: Python Dictionary Comprehension

So it will look something like this:

d = {"item%s" % index: value for (index, value) in enumerate(arr)}

      

Note the use of enumerate to indicate the index of each value in the list.

+1


source


You can also use dict()

to create a dictionary.

d = dict(('item{}'.format(i), arr[i]) for i in xrange(len(arr)))

      

+1


source







All Articles