假设我在Python中有一个列表a,它的条目很方便地映射到一个字典。每个偶数元素表示字典的键,接下来的奇数元素是值

例如,

a = ['hello','world','1','2']

我想把它转换成一个字典b,其中

b['hello'] = 'world'
b['1'] = '2'

在语法上最干净的方法是什么?


当前回答

您也可以尝试这种方法将键和值保存在不同的列表中,然后使用dict方法

data=['test1', '1', 'test2', '2', 'test3', '3', 'test4', '4']

keys=[]
values=[]
for i,j in enumerate(data):
    if i%2==0:
        keys.append(j)
    else:
        values.append(j)

print(dict(zip(keys,values)))

输出:

{'test3': '3', 'test1': '1', 'test2': '2', 'test4': '4'}

其他回答

试试下面的代码:

  >>> d2 = dict([('one',1), ('two', 2), ('three', 3)])
  >>> d2
      {'three': 3, 'two': 2, 'one': 1}

我不确定这是否是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))

也许不是最邪恶的,但是

>>> b = {}
>>> for i in range(0, len(a), 2):
        b[a[i]] = a[i+1]

你也可以这样做(字符串到列表转换,然后转换到字典)

    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

简单的答案

另一个选择(由Alex Martelli提供-来源):

dict(x[i:i+2] for i in range(0, len(x), 2))

相关的注意

如果你有这个:

a = ['bi','double','duo','two']

并且你想要这样(列表中的每个元素键控给定的值(在本例中为2)):

{'bi':2,'double':2,'duo':2,'two':2}

你可以使用:

>>> dict((k,2) for k in a)
{'double': 2, 'bi': 2, 'two': 2, 'duo': 2}