I wish to do this but for a dictionary:
"My string".lower()
Is there a built in function or should I use a loop?
Just use a comprehension to run through the dictionary again and convert all keys to lowercase. If you are using python 3, then use alphabet. items() instead of iteritems .
We are also using the lower() function of Python String to convert the key text to lowercase.
upper() and . lower() string methods are self-explanatory. Performing the . upper() method on a string converts all of the characters to uppercase, whereas the lower() method converts all of the characters to lowercase.
A Python dictionary sub-class that is case-insensitive when searching, but also preserves the keys as inserted. when keys are listed, ie, via keys() or items() methods. pair as the key's value (values become dictionaries).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With