[Tutor] List comprehension for dicts?
Dave Angel
davea at ieee.org
Thu Aug 19 20:27:55 CEST 2010
(You top-posted, so now I have to delete the older part)
Vince Spicer 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()])
>
> hope that helps,
>
> Vince
>
>
The only catch to that is that two or more of the keys may map to the
same uppercase key. If one needs to detect that, one has to write an
explicit loop, rather than just converting with dict()
DaveA
More information about the Tutor
mailing list