Converting list to dict in Python
How to convert a list
my_list = ["a", "b", "c"]
to the dictionary
my_dict = {
1: "a",
2: "b",
3: "c"
}
The keys should be just indices + 1 as in my example.
+3
Jamgreen
source
to share
2 answers
A simple solution:
dict(enumerate(my_list, 1))
For example:
>>> dict(enumerate(["a", "b", "c"], 1))
{1: 'a', 2: 'b', 3: 'c'}
+19
JuniorCompressor
source
to share
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
no coder
source
to share