简体   繁体   English

将字典值(数组)转换为列表

[英]Convert Dictionary values (arrays) into lists

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!谢谢!

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]}
>>> 

you can extract the values of any dict by calling on values()您可以通过调用 values() 来提取任何字典的值

>>> a = {"a":"1"}
>>> a.values()
0: ['1']

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.将数组字典转换为列表字典的一种简单有效的方法是在字典.tolist式中调用.tolist方法。

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]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM