[Tutor] List comprehension for dicts?
Vince Spicer
vince at vinces.ca
Thu Aug 19 17:02:07 CEST 2010
Hey you can use list comprehension here
age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }
you can create a dict from a list of tuples and you can access the dict as
a
list of tuples by accessing its items
Example:
age_dict = dict([(key.upper(), value) for key,value in age_dict.items()])
hope that helps,
Vince
On Thu, Aug 19, 2010 at 8:51 AM, Pete <pkoek11 at xs4all.nl> 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.
>
> http://www.siafoo.net/article/52#dictionary-comprehensions
>
> thanks,
>
> Pete
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100819/2d6bc76f/attachment-0001.html>
More information about the Tutor
mailing list