将列表转换为Python中的字典 [英] Convert a list to a dictionary in Python
问题描述
a
,其条目方便地映射到一个字典。每个偶数元素代表字典的关键字,并且以下奇数元素是值 ,例如
a = ['hello','world','1','2']
,我想将其转换为字典 b
,其中
b ['hello'] ='world'
b ['1'] ='2'
什么是完美的语法上最干净的方法?
code> b = dict(zip(a [0 :: 2],a [1 :: 2]))
如果 a
很大,您可能会想要执行以下操作,这不会产生任何如上所述的临时列表。
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
在Python 3中,您还可以使用字典理解,但讽刺的是,我认为最简单的方法是与 range()
和 len()
,通常是一个代码的气味。
$ b $对于我在范围(0,len(a),2)中的i,b = {a [i]:a [i + 1]}
所以 iter()/ izip()
方法仍然可能是最稳定的在Python 3中,尽管作为注释中的EOL注释,在Python 3中, zip()
已经很懒惰,因此您不需要 izip()
。
i = iter(a)
b = dict(zip(i,i) )
如果你想在一行,你必须欺骗和使用分号。 ; - )
Let's say I have a list a
in Python whose entries conveniently map to a dictionary. Each even element represents the key to the dictionary, and the following odd element is the value
for example,
a = ['hello','world','1','2']
and I'd like to convert it to a dictionary b
, where
b['hello'] = 'world'
b['1'] = '2'
What is the syntactically cleanest way to accomplish this?
b = dict(zip(a[0::2], a[1::2]))
If a
is large, you will probably want to do something like the following, which doesn't make any temporary lists like the above.
from itertools import izip
i = iter(a)
b = dict(izip(i, i))
In Python 3 you could also use a dict comprehension, but ironically I think the simplest way to do it will be with range()
and len()
, which would normally be a code smell.
b = {a[i]: a[i+1] for i in range(0, len(a), 2)}
So the iter()/izip()
method is still probably the most Pythonic in Python 3, although as EOL notes in a comment, zip()
is already lazy in Python 3 so you don't need izip()
.
i = iter(a)
b = dict(zip(i, i))
If you want it on one line, you'll have to cheat and use a semicolon. ;-)
这篇关于将列表转换为Python中的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!