How to convert Python dictionary keys/values to lowercase?

PythonProgramming

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'}
raja
Published on 18-Apr-2018 15:43:39
Advertisements