I wish to do this but for a dictionary:
\"My string\".lower()
Is there a built in function or should I use a loop?
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