Converting list to dict in Python
2 answers
Go to enumerate .
The function enumerate()
adds a counter to the iterable.
Simple example:
for i, v in enumerate(my_list):
print i, v
By default, enumerate()
it starts counting from 0
, but if you give it a second integer argument, it will start with this number:
for i, v in enumerate(my_list, start=1):
print i, v
In your case:
>>> dict(enumerate(your_list, start=1))
{1: 'your_list_value1', 2: 'your_list_value2'}
+6
source to share