Reputation: 1694
and I'm trying to convert dictionary's values to lists. Therefore, I can extend it to another dictionary's values (which are lists) with same keys.
the dictionary looks like this:
Q_VEC_DIC
{'A':array([ 2623.8374 , -1392.9608 , 416.2083 , -1596.7402 ,],dtype=float32),
'B': array([ 1231.1268 , -963.2312 , 1823.7424 , -2295.1428 ,],dtype=float32)}
I've tried the below, but it returns nothing:
ARRAY_TO_LIST=[]
for i in range(len(Q_VEC_DIC)):
DOC=[]
DOC.append(list(Q_VEC_DIC.values())[i].tolist)
ARRAY_TO_LIST.append(DOC)
How can I to convert values into lists by using loops?
Thank you!
Upvotes: 1
Views: 6817
Reputation: 71580
For values do:
>>> d={'a':[1,2,3],'b':['a','b','c']}
>>> d.values()
dict_values([[1, 2, 3], ['a', 'b', 'c']])
>>> list(d.values())
[[1, 2, 3], ['a', 'b', 'c']]
For both keys and values:
>>> list(d.items())
[('a', [1, 2, 3]), ('b', ['a', 'b', 'c'])]
To answer your question do:
>>> import numpy as np
>>> d = {
'A': np.array([2623.8374, -1392.9608, 416.2083, -1596.7402,], dtype=np.float32),
'B': np.array([1231.1268, -963.2312, 1823.7424, -2295.1428,], dtype=np.float32),
}
>>> {k:v.tolist() for k,v in d.items()}
{'A': [2623.83740234375, -1392.9608154296875, 416.20831298828125, -1596.740234375], 'B': [1231.1268310546875, -963.231201171875, 1823.742431640625, -2295.142822265625]}
>>>
Upvotes: 2
Reputation: 55479
A simple and efficient way to convert that dictionary of arrays to a dictionary of lists is to call the .tolist
method in a dictionary comprehension.
import numpy as np
q_vec = {
'A': np.array([2623.8374, -1392.9608, 416.2083, -1596.7402,], dtype=np.float32),
'B': np.array([1231.1268, -963.2312, 1823.7424, -2295.1428,], dtype=np.float32),
}
new_vec = {k: v.tolist() for k, v in q_vec.items()}
print(new_vec)
output
{'A': [2623.83740234375, -1392.9608154296875, 416.20831298828125, -1596.740234375], 'B': [1231.1268310546875, -963.231201171875, 1823.742431640625, -2295.142822265625]}
Upvotes: 0
Reputation: 2218
you can extract the values of any dict by calling on values()
>>> a = {"a":"1"}
>>> a.values()
0: ['1']
Upvotes: 0