将列表转换成字典 [英] Convert list into a dictionary

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

问题描述

l = ["a", "b", "c", "d", "e"]

我想将此列表转换为字典,例如:

I want to convert this list to a dictionary like:

d = {"a": "b", "c": "d", "e": ""}

因此,基本上,偶数将是关键,而几率将是值.我知道我可以通过非Python"方式(例如使用if语句的for循环)来完成此操作,但我相信应该有一种更"pythonic"的方式来完成此操作.因此,感谢您的帮助:)

So basically, the evens will be keys whereas the odds will be values. I know that I can do it in a "non-pythonic" way such as a for loop with if statements but I believe that there should be a more "pythonic" way to accomplish this. So, I appreciate any help :)

推荐答案

使用常规的石斑鱼食谱,您可以这样做:

Using the usual grouper recipe, you could do:

Python 2:

d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))

Python 3:

d = dict(itertools.zip_longest(*[iter(l)] * 2, fillvalue=""))

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

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