dic = {'tiger':'animal','Tiger':'animal','rose':'plant'}
result = {}
for key in dic:
dic[key.lower()] = dic[key] # the key is always in lower case. If it exists already, it will be overriden.
print(result)
dic = {'tiger': 'animal', 'Tiger': 'animal2', 'rose': 'plant'} # example input
newdic = {k.casefold(): v for k, v in dic.items()}
{'rose': 'plant', 'tiger': 'animal2'}
首选小写或大写值
小写字母:
newdic = {k.casefold(): dic.get(k.casefold(), v) for k, v in dic.items()}
{'rose': 'plant', 'tiger': 'animal'}
同样,对于大写:
newdic = {k.capitalize(): dic.get(k.capitalize(), v) for k, v in dic.items()}
{'Rose': 'plant', 'Tiger': 'animal2'}
既然您似乎是一个初学者,我将向您推荐一个更详细的代码:
这应该可以帮助你开始。您可以检查同一个小写键的不同值并抛出错误。你知道吗
有两个选项,其中您有重复的关键点。你知道吗
按插入顺序取最后一个值
在python3.7+(或者作为实现细节的cpython3.6)中,您可以通过插入顺序获取最后一个值。在其他情况下,不应假定秩序。你知道吗
首选小写或大写值
小写字母:
同样,对于大写:
你可以做:
输出
相关问题 更多 >
编程相关推荐