如何在python中将列表转换成字典? [英] How to convert a list into a dictionary in python?

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

问题描述

我有一个对象的列表:

['fb_ads_sm', 'Active', '18 hr ago', '23', 'sm_sg13', 'Pending', '12 hr ago', '0', ...]

如何将其转换为字典,其中键是第1个和第5个元素,值是第2个和第6个元素?

How do I convert this into a dictionary where the keys are the 1st and 5th elements and the values are the 2nd and 6th elements?

dictionary = {'fb_ads_sm': 'Active', 'sm_sg13': 'Pending', ...}

推荐答案

您可以尝试将dict理解与列表切片一起使用

You can try to use dict comprehension with list slicing

a = ['fb_ads_sm', 'Active', '18 hr ago', '23', 'sm_sg13', 'Pending', '12 hr ago']
{k: v for k, v in zip(a[::4], a[1::4])}

OR

dict(zip(a[::4], a[1::4]))

输出

{'fb_ads_sm': 'Active', 'sm_sg13': 'Pending'}

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

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