在Python中将列表转换为字典

问题:在Python中将列表转换为字典

假设我有一个清单 a在Python中,其条目方便地映射到字典。每个偶数元素代表字典的键,后面的奇数元素是值

例如,

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

我想将其转换为字典b

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

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

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?


回答 0

b = dict(zip(a[::2], a[1::2]))

如果a很大,您可能需要执行以下操作,而不会像上面那样创建任何临时列表。

from itertools import izip
i = iter(a)
b = dict(izip(i, i))

在Python 3中,您也可以使用dict理解,但具有讽刺意味的是,我认为最简单的方法是使用range()and len(),通常是代码味道。

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

因此iter()/izip(),尽管EOL在注释中指出,该方法可能仍是Python 3中使用最多的Python语言,但在Python 3 zip()中已经很懒了,因此您不需要izip()

i = iter(a)
b = dict(zip(i, i))

如果您只想一行,就必须作弊并使用分号。;-)

b = dict(zip(a[::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. ;-)


回答 1

简单的答案

另一种选择(礼貌亚历克斯·马尔泰利):

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}

Simple answer

Another option (courtesy of Alex Martellisource):

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

Related note

If you have this:

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

and you want this (each element of the list keying a given value (2 in this case)):

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

you can use:

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

回答 2

您可以很容易地使用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]

You can use a dict comprehension for this pretty easily:

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

my_dict = {item : a[index+1] for index, item in enumerate(a) if index % 2 == 0}

This is equivalent to the for loop below:

my_dict = {}
for index, item in enumerate(a):
    if index % 2 == 0:
        my_dict[item] = a[index+1]

回答 3

我觉得很酷,这是如果您的清单只有2个项目:

ls = ['a', 'b']
dict([ls])
>>> {'a':'b'}

请记住,dict接受任何包含iterable的iterable,其中iterable中的每个项目本身必须是恰好有两个对象的iterable。

Something i find pretty cool, which is that if your list is only 2 items long:

ls = ['a', 'b']
dict([ls])
>>> {'a':'b'}

Remember, dict accepts any iterable containing an iterable where each item in the iterable must itself be an iterable with exactly two objects.


回答 4

可能不是最pythonic的,但是

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

May not be the most pythonic, but

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

回答 5

您可以非常快地完成此操作,而无需创建额外的数组,因此即使在非常大的数组中也可以使用:

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

You can do it pretty fast without creating extra arrays, so this will work even for very large arrays:

dict(izip(*([iter(a)]*2)))

If you have a generator a, even better:

dict(izip(*([a]*2)))

Here’s the rundown:

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

回答 6

您也可以这样操作(在此将字符串转换为列表,然后转换为字典)

    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

You can also do it like this (string to list conversion here, then conversion to a dictionary)

    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

回答 7

对于这种转换,我也非常感兴趣,因为这样的列表是Perl中哈希的默认初始化程序。

这个线程给出了异常全面的答案-

使用Python 2.7生成器表达式,可以发现我是Python的新手。

dict((a[i], a[i + 1]) for i in range(0, len(a) - 1, 2))

I am also very much interested to have a one-liner for this conversion, as far such a list is the default initializer for hashed in Perl.

Exceptionally comprehensive answer is given in this thread –

Mine one I am newbie in Python), using Python 2.7 Generator Expressions, would be:

dict((a[i], a[i + 1]) for i in range(0, len(a) - 1, 2))


回答 8

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

I am not sure if this is pythonic, but seems to work

def alternate_list(a):
   return a[::2], a[1::2]

key_list,value_list = alternate_list(a)
b = dict(zip(key_list,value_list))

回答 9

试试下面的代码:

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

try below code:

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

回答 10

您也可以尝试这种方法将键和值保存在其他列表中,然后使用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'}

You can also try this approach save the keys and values in different list and then use dict method

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

output:

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

回答 11

{x: a[a.index(x)+1] for x in a if a.index(x) % 2 ==0}

result : {'hello': 'world', '1': '2'}
{x: a[a.index(x)+1] for x in a if a.index(x) % 2 ==0}

result : {'hello': 'world', '1': '2'}