这里有字典,我想将一些值设为大写。
# 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())
这将评估为您想要的样子:
dict((k, v if k != "letters" else [x.upper() for x in v]) for k,v in another_dictionary.items())
也许这对您有用吗?首先,您要获取包含key
的letters
并将其替换为列表推导,其中您将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]}
由于您只是尝试更新字母数组,因此可以在数组上使用Python的列表理解功能:
another_dictonary["letters"] = [letter.upper() for letter in another_dictonary["letters"]]
您可以找到有关列表推导如何在Python here中工作的更多信息。