📌  相关文章
📜  Python – 在字典值列表中将字符串转换为大写

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

Python – 在字典值列表中将字符串转换为大写

给定带有值列表的字典,将所有字符串转换为大写。

方法#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))


输出

方法 #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)) 
输出