How to convert Python dictionary keys/values to lowercase?


You can convert Python dictionary keys/values to lowercase by simply iterating over them and creating a new dict from the keys and values. For example,

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))

This will give the output

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

If you want just the keys to be lower cased, you can call lower on just that. For example,

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))

This will give the output

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

Updated on: 17-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements