将键的值转换为大写

问题描述 投票:-1回答:3

这里有字典,我想将一些值设为大写。

# Create a dictionary
another_dictionary = {"numbers": [1, 2, 3], "letters":["a", "b", "c"], "codes":[123, 456, 789]}

我想将字母的所有值都转换为大写。我尝试了很多方法,但没有一个起作用。

第一次尝试:

for letters in another_dictionary["letters"]:
letters = letters.upper()
print(letters)

第二次尝试:

another_dictionary.update({k.lower(): v.upper() for k, v in another_dictionary["letters"].item()})
print(another_dictionary["letters"])

最后尝试:

dict((v.lower(), v) for k,v in another_dictionary["letters"].lower())
python dictionary
3个回答
0
投票

这将评估为您想要的样子:

dict((k, v if k != "letters" else [x.upper() for x in v]) for k,v in another_dictionary.items())

0
投票

也许这对您有用吗?首先,您要获取包含keyletters并将其替换为列表推导,其中您将upper应用于another_dictionary['letters']值中的原始值:

another_dictionary = {"numbers":[1, 2, 3], "letters":["a", "b", "c"], "codes":[123, 456, 789]}
another_dictionary['letters']  = [x.upper() for x in another_dictionary['letters']]

print(another_dictionary)

输出:

{'numbers': [1, 2, 3], 'letters': ['A', 'B', 'C'], 'codes': [123, 456, 789]}

0
投票

由于您只是尝试更新字母数组,因此可以在数组上使用Python的列表理解功能:

another_dictonary["letters"] = [letter.upper() for letter in another_dictonary["letters"]]

您可以找到有关列表推导如何在Python here中工作的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.