简体   繁体   中英

Python: Convert list to a dictionary, where key is the index of the element of the list

I have a list and I want to convert it to a dictionary dict where the key of an element is the position of the element in the list:

>>> 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'}

I know it simple but and there are many ways as one in below:

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

I can't understand totally how collections.defaultdict work, can we use it to achieve the above? Or maybe any other more efficient method?

defaultdict() produces default values , you are generating keys so it won't help you here.

Using enumerate() is the best way; you can simplify that to:

dict(enumerate(list_, 1))

The second argument to enumerate() is the starting value ; setting it to 1 removes the need to increment the count yourself. dict() can consume the (index, value) pairs directly .

You could use defaultdict too.

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

or like below..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM