Python:将列表转换为字典,其中key是列表元素的索引

时间:2016-06-25 15:42:40

标签: python dictionary

我有list,我想将其转换为字典dict,其中元素的键是列表中元素的位置:

>>> list_ = ['a', 'b', 'c', 'd']
>>> # I want the above list to be converted to a dict as shown below
...
>>> list_to_dict = {1: 'a',2: 'b', 3: 'c',4: 'd'}

我知道这很简单,但下面有很多方法:

>>> {index+1: item for index, item in enumerate(list_)}
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

我无法完全理解collections.defaultdict如何运作,我们可以用它来实现上述目标吗?或者可能是其他更有效的方法?

2 个答案:

答案 0 :(得分:6)

defaultdict()生成默认的,您正在生成,因此在这里无法帮助您。

使用enumerate()是最好的方法;你可以简化为:

dict(enumerate(list_, 1))

enumerate()的第二个参数是起始值;将其设置为1可以消除自己递增计数的需要。 dict()可以直接使用(index, value)

答案 1 :(得分:1)

您也可以使用defaultdict。

from collections import defaultdict
list_ = ['a','b','c','d']
s = (zip([i for i in range(1, len(list_) + 1)], list_))
list_to_dict = defaultdict(str)

for k, v in s:
    list_to_dict[k] = v

print list_to_dict

或者像下面一样..

dict(zip([i for i in range(1, len(list_) + 1)], list_))