📜  Python|使用列表索引值初始化字典

📅  最后修改于: 2022-05-13 01:54:19.107000             🧑  作者: Mango

Python|使用列表索引值初始化字典

在使用Python时,我们可能需要执行一些任务,其中我们需要分配一个字典,其中列表值作为字典值,索引作为字典键。在我们需要执行数据类型转换的情况下,这种类型的问题很常见。让我们讨论可以执行此任务的某些方式。

方法 #1:使用字典理解 + len()

可以使用上述函数的组合来执行此任务,其中我们使用字典理解执行字典的构造并使用len函数索引有限。

# Python3 code to demonstrate working of
# Initializing dictionary with list index-values
# Using dictionary comprehension + len()
  
# initializing list
test_list = ['Gfg', 'is', 'best']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing dictionary with list index-values
# Using dictionary comprehension + len()
res = {x : test_list[x] for x in range(len(test_list))}
  
# printing result
print("The dictionary indexed as list is :  " + str(res))
输出 :
The original list is : ['Gfg', 'is', 'best']
The dictionary indexed as list is :  {0: 'Gfg', 1: 'is', 2: 'best'}

方法 #2:使用dict() + enumerate()

这些方法的组合也可用于执行此任务。在此我们使用enumerate函数的质量来获取索引,并使用dict()将列表转换为字典。

# Python3 code to demonstrate working of
# Initializing dictionary with list index-values
# Using dict() + enumerate()
  
# initializing list
test_list = ['Gfg', 'is', 'best']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing dictionary with list index-values
# Using dict() + enumerate()
res = dict(enumerate(test_list))
  
# printing result
print("The dictionary indexed as list is :  " + str(res))
输出 :
The original list is : ['Gfg', 'is', 'best']
The dictionary indexed as list is :  {0: 'Gfg', 1: 'is', 2: 'best'}