Dictionary to lowercase in Python
You will need to use either a loop or a list/generator comprehension. If you want to lowercase all the keys and values, you can do this::
dict((k.lower(), v.lower()) for k,v in {'My Key':'My Value'}.iteritems())
If you want to lowercase just the keys, you can do this::
dict((k.lower(), v) for k,v in {'My Key':'My Value'}.iteritems())
Generator expressions (used above) are often useful in building dictionaries; I use them all the time. All the expressivity of a loop comprehension with none of the memory overhead.
If you want keys and values of multi-nested dictionary (json format) lowercase, this might help. Need to have support for dict comprehensions what should be in Python 2.7
dic = {'A':['XX', 'YY', 'ZZ'],
'B':(u'X', u'Y', u'Z'),
'C':{'D':10,
'E':('X', 'Y', 'Z'),
'F':{'X', 'Y', 'Z'}
},
'G':{'X', 'Y', 'Z'}
}
PYTHON2.7 -- also supports OrderedDict
def _lowercase(obj):
""" Make dictionary lowercase """
if isinstance(obj, dict):
t = type(obj)()
for k, v in obj.items():
t[k.lower()] = _lowercase(v)
return t
elif isinstance(obj, (list, set, tuple)):
t = type(obj)
return t(_lowercase(o) for o in obj)
elif isinstance(obj, basestring):
return obj.lower()
else:
return obj
PYTHON 3.6
def _lowercase(obj):
""" Make dictionary lowercase """
if isinstance(obj, dict):
return {k.lower():_lowercase(v) for k, v in obj.items()}
elif isinstance(obj, (list, set, tuple)):
t = type(obj)
return t(_lowercase(o) for o in obj)
elif isinstance(obj, str):
return obj.lower()
else:
return obj
The following is identical to Rick Copeland's answer, just written without a using generator expression:
outdict = {}
for k, v in {'My Key': 'My Value'}.iteritems():
outdict[k.lower()] = v.lower()
Generator-expressions, list comprehension's and (in Python 2.7 and higher) dict comprehension's are basically ways of rewriting loops.
In Python 2.7+, you can use a dictionary comprehension (it's a single line of code, but you can reformat them to make it more readable):
{k.lower():v.lower()
for k, v in
{'My Key': 'My Value'}.items()
}
They are quite often tidier than the loop equivalent, as you don't have to initialise an empty dict/list/etc.. but, if you need to do anything more than a single function/method call they can quickly become messy.