Python-将嵌套列表转换成字典 [英] Python - Converting nested list into dictionary

查看:1032
本文介绍了Python-将嵌套列表转换成字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a nested list , how do I convert this into a 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并将其转换为字典. 但是我正在寻找从列表到字典的直接转换

I have tried to change into Pandas DataFrame and converted that into dictionary. But I am looking for a direct conversion from list into dictionary

将感谢您的帮助.在Python 3中期待答案

Will appreciate your kind help. Expecting answers in Python 3

推荐答案

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

One way is to use zip, which iterates through i th element of each list sequentially:

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解压缩,以确保您的值是列表.

Unpacking via *v, as suggested by @Jean-FrançoisFabre, ensures your values are lists.

结果

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

这篇关于Python-将嵌套列表转换成字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆