如何将列表转换为以索引为值的字典? [英] How to convert a list to a dictionary with indexes as values?
本文介绍了如何将列表转换为以索引为值的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试转换以下列表:
l = ['A', 'B', 'C']
到像这样的字典:
d = {'A': 0, 'B': 1, 'C': 2}
我已经尝试过其他帖子的答案,但没有一个对我有用.我现在有以下代码:
d = {l[i]: i for i in range(len(l))}
这给了我这个错误:
不可散列的类型:'list'
解决方案
您可以从内置的 enumerate
.你只需要反转索引值映射并使用字典理解来创建字典:
I am trying to convert the following list:
l = ['A', 'B', 'C']
To a dictionary like:
d = {'A': 0, 'B': 1, 'C': 2}
I have tried answers from other posts but none is working for me. I have the following code for now:
d = {l[i]: i for i in range(len(l))}
Which gives me this error:
unhashable type: 'list'
解决方案
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}
这篇关于如何将列表转换为以索引为值的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文