python嵌套列表转为字典,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"]]

where the dictionary should read the below

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

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

Will appreciate your kind help. Expecting answers in Python 3

解决方案

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

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

Result

{'Age': [25, 28, 32, 44],

'Employee': ['001', '002', '003', '004'],

'Gender': ['M', 'M', 'M', 'F'],

'Salary': [1200, 1300, 1400, 1700]}

Another way is to use 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]}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值