0

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} 

3 Answers 3

1

The following should work

a = np.round(a)
d = dict(zip(a[:, 0].astype(str), a[:, 1]))

Note: Equal keys will merge.

Sign up to request clarification or add additional context in comments.

2 Comments

What do you mean by "Equal keys will merge"? Isn't that a characteristic of dictionaries where all the keys have to be unique or am I getting this wrong?
Yes! I mean, if a key appears twice, then the latter one will replace the former. For example, if a=[[1, 2], [1, 3]], then d={'1':3}.
1
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]])

Comments

0

You can convert array to dictionary without any external library. this method uses list comprehension:

assuming input array is in_array and the output dictionary is out_dict

out_dict = {int(x[0]):int(x[1]) for x in in_array}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.