[英]Python: Create dictionary with list index number as key and list element as value?
All the questions I've seen do the exact opposite of what I want to do: 我所看到的所有问题与我想做的事情完全相反:
Say I have a list: 说我有一个清单:
lst = ['a','b','c']
I am looking to make a dictionary where the key is the element number (starting with 1 instead of 0) and the list element is the value. 我正在寻找一个字典,其中的键是元素编号(以1而不是0开头),而list元素是值。 Like this:
像这样:
{1:'a', 2:'b', 3:'c'}
But for a long list. 但名单很长。 I've read a little about enumerate() but everything I've seen has used the list element as the key instead.
我已经阅读了一些有关enumerate()的内容,但是我所看到的所有内容都使用list元素作为键。
I found this: 我找到了这个:
dict = {tuple(key): idx for idx, key in enumerate(lst)}
But that produces: 但这会产生:
{'a':1, 'b':2, 'c':3}
... which is the opposite of what I want. ...这与我想要的相反。 And, also in a weird notation that is confusing to someone new to Python.
而且,这也是一种怪异的表示法,它使刚接触Python的人感到困惑。
Advice is much appreciated! 意见非常感谢! Thanks!
谢谢!
enumerate
has a start
keyword argument so you can count from whatever number you want. enumerate
有一个start
关键字参数,因此您可以从所需的任何数字start
计数。 Then just pass that to dict
然后将其传递给
dict
dict(enumerate(lst, start=1))
You could also write a dictionary comprehension 您还可以编写字典理解
{index: x for index, x in enumerate(lst, start=1)}
Using Dict Comprehension and enumerate 使用Dict理解和枚举
print({x:y for x,y in enumerate(lst,1)})
{1: 'a', 2: 'b', 3: 'c'} {1:“ a”,2:“ b”,3:“ c”}
Using Dict Comprehension , zip and range- 使用Dict Comprehension,zip和range-
print({x:y for x,y in zip(range(1,len(lst)+1),lst)})
{1: 'a', 2: 'b', 3: 'c'} {1:“ a”,2:“ b”,3:“ c”}
By default enumerate start from 0 , but you can set by this value by second argument which is start
, You can add +1 to every iterator if you want to start from 1 instead of zero : 默认情况下,枚举从0开始,但是您可以通过第二个参数
start
来设置此值,如果要从1开始而不是从零开始,则可以向每个迭代器添加+1:
print({index+1:value for index,value in enumerate(lst)})
output: 输出:
{1: 'a', 2: 'b', 3: 'c'}
Above dict comprehension is same as : 上面的dict理解与:
dict_1={}
for index,value in enumerate(lst):
dict_1[index+1]=value
print(dict_1)
I think the below code should help. 我认为以下代码应该有所帮助。
my_list = ['A', 'B', 'C', 'D']
my_index = []
my_dict = {}
for i in range(len(my_list)):
my_index.append(i+1)
for key in my_index:
for value in my_list:
my_dict[key] = value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.