tags:

views:

521

answers:

2

I wish to do this but for a dictionary:

"My string".lower()

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

+18  A: 

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.

Rick Copeland
+5  A: 

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 dict comprehension's (in Python 3.0) are basically ways of rewriting loops.

In Python 3.0, 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.

dbr
+1 for dict comprehension.
Stephan202