Hi guys how would I go on converting numpy arrays as such:
[[ 8.82847075 -5.70925653]
[ 1.07032615 -1.77975378]
[-10.41163742 -0.33042086]
[ 0.23799394 5.5978591 ]
[ 7.7386861 -4.16523845]]
To what I desire in Python 3.10. That includes having the keys and values rounded to the nearest integer:
{'9':-6, '1':-2, '-10':0, '0':6, '8':-4}
CodePudding user response:
dict(zip(*d.round().astype(int).T))
Out: {9: -6, 1: -2, -10: 0, 0: 6, 8: -4}
The data
d = np.array([[ 8.82847075, -5.70925653],
[ 1.07032615, -1.77975378],
[-10.41163742, -0.33042086],
[ 0.23799394, 5.5978591 ],
[ 7.7386861 , -4.16523845]])
CodePudding user response:
The following should work
a = np.round(a)
d = dict(zip(a[:, 0].astype(str), a[:, 1]))
Note: Equal keys will merge.
CodePudding user response:
I would do this with a list comprehension:
import numpy as np
data = np.array([[8.82847075,-5.70925653],[1.07032615,-1.77975378],[-10.41163742,-0.33042086],[0.23799394,5.5978591],[7.7386861,-4.16523845]])
data_dict = { int(round(x)):int(round(y)) for x,y in data}
data_dict
>>>{9: -6, 1: -2, -10: 0, 0: 6, 8: -4}
CodePudding user response:
Try using this function:
arrayToDictionary(x:list):
tempDictionary = dict()
for value in x:
x = str(int(x[0]))
y = int(x[1])
tempDictionary[x] = y
return tempDictionary
# then call the function using:
print(arrayToDictionary(yourarray))