Python – 为字典中的每个键名添加前缀
给定一个字典,通过为每个键添加前缀来更新它的每个键。
Input : test_dict = {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9}, temp = “Pro”
Output : {‘ProGfg’ : 6, ‘Prois’ : 7, ‘Probest’ : 9}
Explanation : “Pro” prefix added to each key.
Input : test_dict = {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9}, temp = “a”
Output : {‘aGfg’ : 6, ‘ais’ : 7, ‘abest’ : 9}
Explanation : “a” prefix added to each key.
方法#1:使用字典理解
这是可以执行此任务的方法之一。在此,我们通过执行前缀与所有键的连接来构造新字典。
Python3
# Python3 code to demonstrate working of
# Add prefix to each key name in dictionary
# Using loop
# initializing dictionary
test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing prefix
temp = "Pro"
# + operator is used to perform task of concatenation
res = {temp + str(key): val for key, val in test_dict.items()}
# printing result
print("The extracted dictionary : " + str(res))
Python3
# Python3 code to demonstrate working of
# Add prefix to each key name in dictionary
# Using f strings + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing prefix
temp = "Pro"
# dictionary comprehension is used to bind result
# f strings are used to bind prefix with key
res = {f"Pro{key}": val for key, val in test_dict.items()}
# printing result
print("The extracted dictionary : " + str(res))
输出
The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}
The extracted dictionary : {'ProGfg': 6, 'Prois': 7, 'Probest': 9, 'Profor': 8, 'Progeeks': 11}
方法#2:使用 f字符串+ 字典理解
上述功能的组合可以用来解决这个问题。在此,我们使用 f 个字符串执行连接任务。仅适用于 >=3.6 版本的Python。
Python3
# Python3 code to demonstrate working of
# Add prefix to each key name in dictionary
# Using f strings + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing prefix
temp = "Pro"
# dictionary comprehension is used to bind result
# f strings are used to bind prefix with key
res = {f"Pro{key}": val for key, val in test_dict.items()}
# printing result
print("The extracted dictionary : " + str(res))
输出
The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}
The extracted dictionary : {'ProGfg': 6, 'Prois': 7, 'Probest': 9, 'Profor': 8, 'Progeeks': 11}