python转换列表到字典 [英] python convert list to dictionary

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

问题描述

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

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

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


$ b $所以基本上,这个evens将是key,而odds将是值。我知道我可以以非pythonic的方式来执行,例如一个for语句的循环,但是我相信应该有更多的pythonic的方式来完成这个。所以,我感谢任何帮助:)

解决方案

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



Python 2: strong>

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

Python 3:

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

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

I want to convert this list to a dictionary like:

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

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=""))

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

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