📜  Python - 从列表中创建字典

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

Python - 从列表中创建字典

给出一个列表。任务是将其转换为字典,其中值作为列表元素,键作为给定字符串K 和值的串联。

例子:

方法#1:使用循环

这是可以执行此任务的方法之一。在此,我们使用 +运算符执行连接以构造键,并从列表中提取值。

Python3
# Python3 code to demonstrate working of 
# Values derived Dictionary keys
# Using loop
  
# initializing list
test_list = ["gfg", "is", "best"] 
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = "def_key_"
  
# using loop to construct new Dictionary
# + operator used to concat default key and values 
res = dict()
for ele in test_list:
    res[K + str(ele)] = ele 
  
# printing result 
print("The constructed Dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Values derived Dictionary keys
# Using dictionary comprehension
  
# initializing list
test_list = ["gfg", "is", "best"] 
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = "def_key_"
  
# using dictionary comprehension
# + operator used to concat default key and values 
res = {K + str(ele) : ele for ele in test_list}
  
# printing result 
print("The constructed Dictionary : " + str(res))


输出:

方法#2:使用字典理解

这是可以执行此任务的另一种方式。在此,我们使用字典理解使用单行构建字典。

蟒蛇3

# Python3 code to demonstrate working of 
# Values derived Dictionary keys
# Using dictionary comprehension
  
# initializing list
test_list = ["gfg", "is", "best"] 
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = "def_key_"
  
# using dictionary comprehension
# + operator used to concat default key and values 
res = {K + str(ele) : ele for ele in test_list}
  
# printing result 
print("The constructed Dictionary : " + str(res))

输出: