Python – 在字典值列表中将字符串转换为大写
给定带有值列表的字典,将所有字符串转换为大写。
Input : {“Gfg” : [“ab”, “cd”], “Best” : [“gh”], “is” : [“kl”]}
Output : {‘Gfg’: [‘AB’, ‘CD’], ‘Best’: [‘GH’], ‘is’: [‘KL’]}
Explanation : All value lists strings are converted to upper case.
Input : {“Gfg” : [“ab”, “cd”, “Ef”]}
Output : {‘Gfg’: [‘AB’, ‘CD’, “EF”]}
Explanation : All value lists strings are converted to upper case, already upper case have no effect.
方法#1:使用字典理解+upper()+列表理解
上述功能的组合可以用来解决这个问题。在此,我们使用 upper() 执行大写,列表推导用于遍历所有字符串,字典推导用于使用大写值重新制作字典。
Python3
# Python3 code to demonstrate working of
# Convert Strings to Uppercase in Dictionary value lists
# Using dictionary comprehension + upper() + list comprehension
# initializing dictionary
test_dict = {"Gfg" : ["ab", "cd", "ef"],
"Best" : ["gh", "ij"], "is" : ["kl"]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using upper to convert to upper case
res = {key: [ele.upper() for ele in test_dict[key] ] for key in test_dict }
# printing result
print("The dictionary after conversion " + str(res))
Python3
# Python3 code to demonstrate working of
# Convert Strings to Uppercase in Dictionary value lists
# Using map() + upper() + dictionary comprehension
# initializing dictionary
test_dict = {"Gfg" : ["ab", "cd", "ef"],
"Best" : ["gh", "ij"], "is" : ["kl"]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using map() to extend logic to all inner list
res = {key: list(map(str.upper, test_dict[key])) for key in test_dict}
# printing result
print("The dictionary after conversion " + str(res))
The original dictionary is : {‘Gfg’: [‘ab’, ‘cd’, ‘ef’], ‘Best’: [‘gh’, ‘ij’], ‘is’: [‘kl’]}
The dictionary after conversion {‘Gfg’: [‘AB’, ‘CD’, ‘EF’], ‘Best’: [‘GH’, ‘IJ’], ‘is’: [‘KL’]}
方法 #2:使用 map() + upper() + 字典理解
上述功能的组合可以用来解决这个问题。在此,我们使用 map() 而不是列表推导来执行扩展大写逻辑的任务。
Python3
# Python3 code to demonstrate working of
# Convert Strings to Uppercase in Dictionary value lists
# Using map() + upper() + dictionary comprehension
# initializing dictionary
test_dict = {"Gfg" : ["ab", "cd", "ef"],
"Best" : ["gh", "ij"], "is" : ["kl"]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using map() to extend logic to all inner list
res = {key: list(map(str.upper, test_dict[key])) for key in test_dict}
# printing result
print("The dictionary after conversion " + str(res))
The original dictionary is : {‘Gfg’: [‘ab’, ‘cd’, ‘ef’], ‘Best’: [‘gh’, ‘ij’], ‘is’: [‘kl’]}
The dictionary after conversion {‘Gfg’: [‘AB’, ‘CD’, ‘EF’], ‘Best’: [‘GH’, ‘IJ’], ‘is’: [‘KL’]}