假设我在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'
在语法上最干净的方法是什么?
当前回答
你可以在不创建额外数组的情况下非常快地完成它,所以这即使对于非常大的数组也适用:
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
其他回答
{x: a[a.index(x)+1] for x in a if a.index(x) % 2 ==0}
result : {'hello': 'world', '1': '2'}
我不确定这是否是pythonic,但似乎工作
def alternate_list(a):
return a[::2], a[1::2]
key_list,value_list = alternate_list(a)
b = dict(zip(key_list,value_list))
我还非常希望有一个用于此转换的一行程序,因为这样的列表是Perl中哈希的默认初始化式。
在这篇文章中给出了非常全面的答案
Python转换列表到字典
我的一个我是Python新手),使用Python 2.7生成器表达式,将是:
dict([我],[i + 1])我的范围(0,len (a) - 1, 2))
你也可以这样做(字符串到列表转换,然后转换到字典)
string_list = """
Hello World
Goodbye Night
Great Day
Final Sunset
""".split()
string_list = dict(zip(string_list[::2],string_list[1::2]))
print string_list
试试下面的代码:
>>> d2 = dict([('one',1), ('two', 2), ('three', 3)])
>>> d2
{'three': 3, 'two': 2, 'one': 1}