basically I want to know that how to convert array into dictionary in python.
import numpy as np
a=np.array(\[23,34,23,45,23\])
print(a)
output [23 34 23 45 23]
but i want
{0:"23",1:"34",2:"23",3:"45",4:"23"}
CodePudding user response:
It seems that the values in the array need to be converted to string when added to the target dictionary. Therefore:
import numpy as np
a = np.array([23,34,23,45,23])
d = dict(enumerate(map(str, a)))
print(d)
Output:
{0: '23', 1: '34', 2: '23', 3: '45', 4: '23'}
CodePudding user response:
Iteratively by enumerate() and using f-formatting for dict-members
mydict={}
for index, i in enumerate(a):
mydict[index]=f"{i}"
print(mydict)
f-formatting: https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498
CodePudding user response:
You can use comprehensions like
dic={i:a[i] for i in range(len(a))}