如何将字典和数组转换为列表?

时间:2018-05-18 08:02:19

标签: python python-3.x list

我有一个字典“a”和一个数组“b”

“a”看起来有点像这样:

{Volvo: 657898, Volkswagen: 387564}... etc

和“b”看起来像这样:

[['Volvo' 'VO']
['Volkswagen' 'VW']]
... etc 

如何比较它们,并制作如下所示的列表:

[['Volvo', 'VO', 657898],
['Volkswagen', 'VW', 387564],
etc...

2 个答案:

答案 0 :(得分:1)

您可以使用列表理解

result = [item + [a[item[0]]] for item in b]

输出

[['Volvo', 'VO', 657898], ['Volkswagen', 'VW', 387564]]

答案 1 :(得分:1)

使用for-loop

<强>演示:

import numpy as np
d = {"Volvo": 657898, "Volkswagen": 387564}
l = np.array([['Volvo', 'VO'],['Volkswagen', 'VW']]).tolist()

for i in l:
    i.append(d.get(i[0]))
print(l)   #If you want to convert it back to numpy array use l = np.asarray(l)

<强>输出:

[['Volvo', 'VO', 657898], ['Volkswagen', 'VW', 387564]]