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

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

问题描述

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

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

I want to convert this list to a dictionary like:

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

所以基本上,偶数将是关键,而赔率将是值.我知道我可以用非 Pythonic"的方式来做到这一点,比如带有 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 :)

推荐答案

使用通常的 grouper食谱,你可以这样做:

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天全站免登陆