Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary to lowercase in Python

I wish to do this but for a dictionary:

"My string".lower() 

Is there a built in function or should I use a loop?

like image 356
Teifion Avatar asked Apr 18 '09 21:04

Teifion


People also ask

How do you convert a dictionary to lowercase in Python?

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 .

How do you make a lowercase key in Python?

We are also using the lower() function of Python String to convert the key text to lowercase.

How do you convert a uppercase letter to a lowercase in Python?

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.

Is dictionary in Python case sensitive?

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).


2 Answers

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.

like image 101
Rick Copeland Avatar answered Sep 20 '22 14:09

Rick Copeland


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.

like image 44
dbr Avatar answered Sep 18 '22 14:09

dbr