如何将 Python 字典的键/值转换为小写?

pythonprogramming更新于 2024/4/11 11:43:00

只需对 Python 字典的键/值进行迭代,然后根据键和值创建一个新的字典,即可将其转换为小写。例如,

def lower_dict(d):
   new_dict = dict((k.lower(), v.lower()) for k, v in d.items())
   return new_dict
a = {'Foo': "Hello", 'Bar': "World"}
print(lower_dict(a))

将给出输出

{'foo': 'hello', 'bar': 'world'}

如果您只希望键为小写,则可以调用 lower。例如,

def lower_dict(d):
   new_dict = dict((k.lower(), v) for k, v in d.items())
   return new_dict
a = {'Foo': "Hello", 'Bar': "World"}
print(lower_dict(a))

这将给出输出

{'foo': 'Hello', 'bar': 'World'}

相关文章