Python - 从列表中创建字典
给出一个列表。任务是将其转换为字典,其中值作为列表元素,键作为给定字符串K 和值的串联。
例子:
Input : test_list = [“gfg”, “is”, “best”], K = “pref_”
Output : {‘pref_gfg’: ‘gfg’, ‘pref_is’: ‘is’, ‘pref_best’: ‘best’}
Explanation : Keys constructed after concatenating K.
Input : test_list = [“gfg”, “best”], K = “pref_”
Output : {‘pref_gfg’: ‘gfg’, ‘pref_best’: ‘best’}
Explanation : Keys constructed after concatenating 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))
输出:
The original list is : [‘gfg’, ‘is’, ‘best’]
The constructed Dictionary : {‘def_key_gfg’: ‘gfg’, ‘def_key_is’: ‘is’, ‘def_key_best’: ‘best’}
方法#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))
输出:
The original list is : [‘gfg’, ‘is’, ‘best’]
The constructed Dictionary : {‘def_key_gfg’: ‘gfg’, ‘def_key_is’: ‘is’, ‘def_key_best’: ‘best’}