How can I convert a list
my_list = ["a", "b", "c"]
into a dictionary
my_dict = {
1: "a",
2: "b",
3: "c"
}
The keys should just be the indexes + 1 as in my example.
A simple solution is:
dict(enumerate(my_list, 1))
For example:
>>> dict(enumerate(["a", "b", "c"], 1))
{1: 'a', 2: 'b', 3: 'c'}
Go for enumerate .
The enumerate()
function adds a counter to an iterable.
Simple example:
for i, v in enumerate(my_list):
print i, v
By default, enumerate()
starts counting at 0
but if you give it a second integer argument, it'll start from that number instead:
for i, v in enumerate(my_list, start=1):
print i, v
For your case:
>>> dict(enumerate(your_list, start=1))
{1: 'your_list_value1', 2: 'your_list_value2'}
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.