python - 如何将列表转换为以索引为值的字典?

标签 python dictionary

我正在尝试转换以下列表:

l = ['A', 'B', 'C']

到像这样的字典:

d = {'A': 0, 'B': 1, 'C': 2}

我尝试过其他帖子的答案,但没有一个对我有用。我现在有以下代码:

d = {l[i]: i for i in range(len(l))}

这给了我这个错误:

unhashable type: 'list'

最佳答案

您可以从内置的 enumerate 中获取列表的索引。 .您只需要反转索引值映射并使用字典推导来创建字典:

>>> lst = ['A', 'B', 'C']
>>> {k: v for v, k in enumerate(lst)}
{'A': 0, 'C': 2, 'B': 1}

关于python - 如何将列表转换为以索引为值的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36459969/

相关文章:

python - 从文本文件创建字典 2 个值

python - TypeError : must be convertible to a buffer, 不是 HTTPResponse

iphone - Swift 中的字典不起作用?

dictionary - 匿名结构,结构{}{}和{}的区别

python - 在 Python 中获取列表的值

python - Python 中的辛普森规则

python - Numpy 数组广播规则

python - Bootstrap 方法和置信区间

c++ - map 键没有可行的重载 '=' 错误

python - 检索存储在字典中的类实例的属性