![](/img/trans.png)
[英]convert/map python dictionary to a list, by using the key as the list index
[英]Python: Convert list to a dictionary, where key is the index of the element of the list
我有一个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
如何工作的,我们可以用它来实现上述目标吗? 也许还有其他更有效的方法?
defaultdict()
产生默认值 ,您正在生成密钥,因此这里无济于事。
使用enumerate()
是最好的方法。 您可以简化为:
dict(enumerate(list_, 1))
enumerate()
的第二个参数是起始值 ; 将其设置为1无需您自己增加计数。 dict()
可消耗的(index, value)
直接对。
您也可以使用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_))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.