I wish to do this but for a dictionary:
\"My string\".lower()
Is there a built in function or should I use a loop?
In Python 3
you can do:
dict((k.lower(), v.lower()) for k,v in {'Key':'Value'}.items())
In Python 2
just substitute .items()
for .iteritems()
:
dict((k.lower(), v.lower()) for k,v in {'Key':'Value'}.iteritems())
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
In Python 3:
d = dict()
d = {k.casefold(): v for k, v in d.items()}
If the dictionary supplied have multiple type of key/values(numeric, string etc.); then use the following solution.
For example; if you have a dictionary named mydict as shown below
mydict = {"FName":"John","LName":"Doe",007:true}
In Python 2.x
dict((k.lower() if isinstance(k, basestring) else k, v.lower() if isinstance(v, basestring) else v) for k,v in mydict.iteritems())
In Python 3.x
dict((k.lower() if isinstance(k, str) else k, v.lower() if isinstance(v, str) else v) for k,v in mydict.iteritems())
Note: this works good on single dimensional dictionaries
I am answering this late - as the question is tagged Python
.
Hence answering with a solution for both Python 2.x
and Python 3.x
, and also handling the case of non-string keys.
Python 2.x - using dictionary comprehension
{k.lower() if isinstance(k, basestring) else k: v.lower() if isinstance(v, basestring) else v for k,v in yourDict.iteritems()}
Demo:
>>> yourDict = {"Domain":"WORKGROUP", "Name": "CA-LTP-JOHN", 111: 'OK', "Is_ADServer": 0, "Is_ConnectionBroker": 0, "Domain_Pingable": 0}
>>> {k.lower() if isinstance(k, basestring) else k: v.lower() if isinstance(v, basestring) else v for k,v in yourDict.iteritems()}
{'domain': 'workgroup', 'name': 'ca-ltp-john', 'is_adserver': 0, 'is_connectionbroker': 0, 111: 'ok', 'domain_pingable': 0}
Python 3.x - no iteritems()
in Python 3.x
{k.lower() if isinstance(k, str) else k: v.lower() if isinstance(v, str) else v for k,v in yourDict.items()}
Demo:
>>> dict((k.lower() if isinstance(k, basestring) else k, v.lower() if isinstance(v, basestring) else v) for k,v in yourDict.iteritems())
Traceback (most recent call last):
File "python", line 1, in <module>
AttributeError: 'dict' object has no attribute 'iteritems'
>>> {k.lower() if isinstance(k, str) else k: v.lower() if isinstance(v, str) else v for k,v in yourDict.items()}
>>> {'domain': 'workgroup', 'name': 'ca-ltp-john', 111: 'ok', 'is_adserver': 0, 'is_connectionbroker': 0, 'domain_pingable': 0}
This will lowercase all your dict keys. Even if you have nested dict or lists. You can do something similar to apply other transformations.
def lowercase_keys(obj):
if isinstance(obj, dict):
obj = {key.lower(): value for key, value in obj.items()}
for key, value in obj.items():
if isinstance(value, list):
for idx, item in enumerate(value):
value[idx] = lowercase_keys(item)
obj[key] = lowercase_keys(value)
return obj
json_str = {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}], "EMB_DICT": {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}]}}
lowercase_keys(json_str)
Out[0]: {'foo': 'BAR',
'bar': 123,
'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}],
'emb_dict': {'foo': 'BAR',
'bar': 123,
'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}]}}