Python - 将嵌套列表转换为字典

时间:2018-03-12 14:48:22

标签: python list dictionary

我有一个嵌套列表,如何将其转换为字典

data = [["Employee","Salary","Age","Gender"],["001",1200,25,"M"],["002",1300,28,"M"],["003",1400,32,"M"],["004",1700,44,"F"]]

字典应该在下面阅读

dict = {'Employee':['001','002','003','004'],'Salary':[1200,1300,1400,1700],'Age':[25,28,32,44],'Gender':['M','M','M','F']}

我尝试更改为Pandas DataFrame并将其转换为字典。 但我正在寻找从列表到字典的直接转换

非常感谢您的帮助。期待Python 3中的答案

1 个答案:

答案 0 :(得分:10)

一种方法是使用zip,它按顺序遍历每个列表的 i 元素:

data = [["Employee","Salary","Age","Gender"],
        ["001",1200,25,"M"],
        ["002",1300,28,"M"],
        ["003",1400,32,"M"],
        ["004",1700,44,"F"]]

d = {k: v for k, *v in zip(*data)}

按照@ Jean-FrançoisFabre的建议,通过*v解包,确保您的值为列表。

<强>结果

{'Age': [25, 28, 32, 44],
 'Employee': ['001', '002', '003', '004'],
 'Gender': ['M', 'M', 'M', 'F'],
 'Salary': [1200, 1300, 1400, 1700]}

另一种方法是使用pandas

import pandas as pd

df = pd.DataFrame(data[1:], columns=data[0]).to_dict('list')

# {'Age': [25, 28, 32, 44],
#  'Employee': ['001', '002', '003', '004'],
#  'Gender': ['M', 'M', 'M', 'F'],
#  'Salary': [1200, 1300, 1400, 1700]}