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?
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?
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'}
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}
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.
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}
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.
You can also use the dict()
to construct your dictionary.
d = dict(('item{}'.format(i), arr[i]) for i in xrange(len(arr)))
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}]