[Tutor] List comprehension for dicts?

Peter Otten __peter__ at web.de
Thu Aug 19 17:20:18 CEST 2010


Pete wrote:

> Hi,
> 
> I've been reading up on list comprehensions lately, all userful and
> powerful stuff - trying to wrap my brain around it :)
> 
> As the examples all seem to relate to lists, I was wondering if there is
> an elegant similar way to apply a function to all keys in a dictionary?
> 
> (without looping over it, of course)
> 
> I'm trying to convert all keys in a dict to uppercase, as in:
> 
> INPUT:
> age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }
> 
> OUTPUT:
> age_dict = { 'PETE': 42, 'ANN': 25, 'CARL': 30, 'AMANDA': 64 }
> 
> I googled 'dictionary comprehension' but couldn't get any code to work
> with the examples given.

Python 2.4-2.6
>>> dict((k.upper(), v) for k, v in age_dict.iteritems())
{'PETE': 42, 'ANN': 25, 'AMANDA': 64, 'CARL': 30}

Python 2.7
>>> {k.upper(): v for k, v in age_dict.iteritems()}
{'PETE': 42, 'ANN': 25, 'AMANDA': 64, 'CARL': 30}


Python 3.x
>>> {k.upper(): v for k, v in age_dict.items()}
{'PETE': 42, 'ANN': 25, 'AMANDA': 64, 'CARL': 30}


items() instead of iteritems() works in 2.x, too, but is less efficient.

Peter



More information about the Tutor mailing list