简体   繁体   English

在Python中将列表转换为dict

[英]Convert list to dict in Python

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. 键应该只是索引+ 1,如我的例子中所示。

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. enumerate()函数向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: 默认情况下, enumerate()0开始计数,但如果给它第二个整数参数,它将从该数字开始:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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