[Tutor] List comprehension for dicts?
Wayne Werner
waynejwerner at gmail.com
Thu Aug 19 17:40:54 CEST 2010
On Thu, Aug 19, 2010 at 10:02 AM, Vince Spicer <vince at vinces.ca> wrote:
> 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()])
>
This is a bad place to use a list comprehension. This will create a list of
values first and then create a dict from that list, so now you have a list
floating around that you didn't need.
Generator expressions, OTOH, generate the values on the fly, only as they're
needed, so there's no extra list left over once the dict is created.
Sure it will eventually be garbage collected, but "waste not, want not", as
my grandmother used to say.
-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100819/8106fc2f/attachment.html>
More information about the Tutor
mailing list