Reputation: 2154
Now, I wanna convert an array to a dict like this:
dict = {'item0': arr[0], 'item1': arr[1], 'item2': arr[2]...}
How to solve this problem elegantly in python?
Upvotes: 3
Views: 5493
Reputation: 151
Using map
, this could be solved as:
a = [1, 2, 3]
d = list(map(lambda x: {f"item{x[0]}":x[1]}, enumerate(a)))
The result is:
[{'item0': 1}, {'item1': 2}, {'item2': 3}]
Upvotes: 0
Reputation: 9647
You can also use the dict()
to construct your dictionary.
d = dict(('item{}'.format(i), arr[i]) for i in xrange(len(arr)))
Upvotes: 2
Reputation: 1103
Use dictionary comprehension: Python Dictionary Comprehension
So it'll look something like:
d = {"item%s" % index: value for (index, value) in enumerate(arr)}
Note the use of enumerate to give the index of each value in the list.
Upvotes: 1
Reputation: 1104
you could use a dictionary comprehension eg.
>>> x = [1,2,3]
>>> {'item'+str(i):v for i, v in enumerate(x)}
>>> {'item2': 3, 'item0': 1, 'item1': 2}
Upvotes: 1
Reputation: 2450
simpleArray = [ 2, 54, 32 ]
simpleDict = dict()
for index,item in enumerate(simpleArray):
simpleDict["item{0}".format(index)] = item
print(simpleDict)
Ok, first line Is the input, second line is an empty dictionary. We will fill it on the fly.
Now we need to iterate, but normal iteration as in C is considered non Pythonic. Enumerate will give the index and the item we need from the array. See this: Accessing the index in Python 'for' loops.
So in each iteration we will be getting an item from array and inserting in the dictionary with a key from the string in brackets. I'm using format since use of % is discouraged. See here: Python string formatting: % vs. .format.
At last we will print. Used print as function for more compatibility.
Upvotes: 1
Reputation: 353169
You could use enumerate
and a dictionary comprehension:
>>> arr = ["aa", "bb", "cc"]
>>> {'item{}'.format(i): x for i,x in enumerate(arr)}
{'item2': 'cc', 'item0': 'aa', 'item1': 'bb'}
Upvotes: 13
Reputation: 6466
Suppose we have a list of int
s:
We can use a 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}
Upvotes: 2