Python:将列表转换为带索引的字典 [英] Python: Convert list to dictionary with indexes

查看:581
本文介绍了Python:将列表转换为带索引的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to convert the following list:

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

到像这样的字典

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

我尝试了其他帖子的答案,但对我没有用.我现在有以下代码:

I have tried answers from other posts none which is working for me. I have the following code for now:

{list[i]: i for i in range(len(list))}

哪个给我这个错误:

unhashable type: 'list'

我们非常感谢您的帮助.谢谢.

Any help is much appreciated. Thanks.

推荐答案

您可以从内置的

You can get the indices of a list from the built-in enumerate. You just need to reverse the index value map and use a dictionary comprehension to create a dictionary

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

哦,永远不要将变量命名为内置变量或类型.

Ohh, and never name a variable to a built-in or a type.

这篇关于Python:将列表转换为带索引的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆