wolframalpha wolframalpha - 1 year ago 183
Python Question

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

I have a

and I want to convert it to a dictionary
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
work, can we use it to achieve the above? Or maybe any other more efficient method?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download