假设我在Python中有一个列表a,它的条目很方便地映射到一个字典。每个偶数元素表示字典的键,接下来的奇数元素是值
例如,
a = ['hello','world','1','2']
我想把它转换成一个字典b,其中
b['hello'] = 'world'
b['1'] = '2'
在语法上最干净的方法是什么?
假设我在Python中有一个列表a,它的条目很方便地映射到一个字典。每个偶数元素表示字典的键,接下来的奇数元素是值
例如,
a = ['hello','world','1','2']
我想把它转换成一个字典b,其中
b['hello'] = 'world'
b['1'] = '2'
在语法上最干净的方法是什么?
当前回答
b = dict(zip(a[::2], a[1::2]))
如果a很大,您可能会想要执行如下操作,它不会像上面那样生成任何临时列表。
from itertools import izip
i = iter(a)
b = dict(izip(i, i))
在Python 3中,你也可以使用字典理解,但讽刺的是,我认为最简单的方法是使用range()和len(),这通常是一种代码气味。
b = {a[i]: a[i+1] for i in range(0, len(a), 2)}
因此iter()/izip()方法可能仍然是Python 3中最Python化的方法,尽管正如EOL在注释中指出的那样,zip()在Python 3中已经是惰性的,所以你不需要izip()。
i = iter(a)
b = dict(zip(i, i))
在Python 3.8及以后版本中,您可以使用"walrus"操作符(:=)将其写在一行中:
b = dict(zip(i := iter(a), i))
否则,您需要使用分号将其放在一行上。
其他回答
你可以在不创建额外数组的情况下非常快地完成它,所以这即使对于非常大的数组也适用:
dict(izip(*([iter(a)]*2)))
如果你有一个发电机a,那就更好了:
dict(izip(*([a]*2)))
以下是梗概:
iter(h) #create an iterator from the array, no copies here
[]*2 #creates an array with two copies of the same iterator, the trick
izip(*()) #consumes the two iterators creating a tuple
dict() #puts the tuples into key,value of the dictionary
b = dict(zip(a[::2], a[1::2]))
如果a很大,您可能会想要执行如下操作,它不会像上面那样生成任何临时列表。
from itertools import izip
i = iter(a)
b = dict(izip(i, i))
在Python 3中,你也可以使用字典理解,但讽刺的是,我认为最简单的方法是使用range()和len(),这通常是一种代码气味。
b = {a[i]: a[i+1] for i in range(0, len(a), 2)}
因此iter()/izip()方法可能仍然是Python 3中最Python化的方法,尽管正如EOL在注释中指出的那样,zip()在Python 3中已经是惰性的,所以你不需要izip()。
i = iter(a)
b = dict(zip(i, i))
在Python 3.8及以后版本中,您可以使用"walrus"操作符(:=)将其写在一行中:
b = dict(zip(i := iter(a), i))
否则,您需要使用分号将其放在一行上。
{x: a[a.index(x)+1] for x in a if a.index(x) % 2 ==0}
result : {'hello': 'world', '1': '2'}
我觉得很酷的是,如果你的清单只有两项:
ls = ['a', 'b']
dict([ls])
>>> {'a':'b'}
记住,dict接受任何包含可迭代对象的可迭代对象,其中可迭代对象中的每一项本身必须是恰好包含两个对象的可迭代对象。
你可以很容易地使用字典理解:
a = ['hello','world','1','2']
my_dict = {item : a[index+1] for index, item in enumerate(a) if index % 2 == 0}
这相当于下面的for循环:
my_dict = {}
for index, item in enumerate(a):
if index % 2 == 0:
my_dict[item] = a[index+1]