I have a dictionary like this:
import array as ar
import numpy as np
dict = {}
for i in range(3): dict[i]=ar.array('I')
dict[0]=np.array([1,2,3], dtype='int')
dict[1]=np.array([], dtype='int')
dict[2]=np.array([7,5], dtype='int')
And the dictionary is basically like this:
0: 1,2,3
1: []
2: 7,5
And I want to get an output array like this:
array([[0,0,0,2,2],[1,2,3,7,5]])
So the first row is the keys in the dictionary, and the second row is the corresponding items in the dictionary. If the items are empty, then remove the keys in the output array. How to generate the array from the input dict
in python?
I have a for-loop version:
aa = np.hstack([[k]*len(v) for k,v in dict.items()])
bb = np.hstack([v for k,v in dict.items()])
res = np.vstack((aa, bb))
But it somehow changes the dtype
to float64
. I am looking for a better solution.
Slight modification on your answer:
Change res = np.vstack((aa, bb))
into res = np.array((aa, bb), dtype=int)
.
import array as ar
import numpy as np
#dict = {}
# why so difficult?
#for i in range(3):
# dict[i]=ar.array('I')
#dict[0]=np.array([1,2,3], dtype='int')
#dict[1]=np.array([], dtype='int')
#dict[2]=np.array([7,5], dtype='int')
dict = {0: [1,2,3],
1: [],
2: [7,5]}
print(dict)
aa = np.hstack([[k]*len(v) for k,v in dict.items()])
bb = np.hstack([v for k,v in dict.items()])
res = np.array((aa, bb), dtype=int)
print(res)
If required for testing you can always add a dot for floating point dtype as per... if you print the dict:
dict = {0: [1,2,3.], # here 3. is float
1: [],
2: [7,5]}
The final result is "int" dtype array anyway.
Solution with for
loops:
keys = []
values = []
for k, v in dict.items():
for i in v:
keys += [k]
values += [i]
result = array([keys, values])
Solution without for
loops:
w = [[[k]*len(v), v] for k, v in dict.items()]
result = array([[y for x in [q[0] for q in w] for y in x], [y for x in [q[1] for q in w] for y in x]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.