[dictionary] how to get key by item
Delaney, Timothy C (Timothy)
tdelaney at avaya.com
Mon Dec 13 21:06:17 EST 2004
Roy Smith wrote:
>> >>> forward = {10 : 50, 2 : 12, 4 : 43}
>> >>> reverse = dict([(v,k) for (k,v) in forward.iteritems()])
>> >>> print forward {10: 50, 4: 43, 2: 12}
>> >>> print reverse
>> {50: 10, 43: 4, 12: 2}
>
> BTW, does Python really build the intermediate list and throw it away
> after using it to initialize the dictionary, or is it smart enough to
> know that it doesn't really need to build the whole list in memory?
Python will do what you tell it. In the above case, it will build a
list.
Using Python 2.4, the above can be rewritten as a generator expression:
>>> forward = {10 : 50, 2 : 12, 4 : 43}
>>> reverse = dict((v,k) for (k,v) in forward.iteritems())
>>> print forward {10: 50, 4: 43, 2: 12}
>>> print reverse
{50: 10, 43: 4, 12: 2}
which does not build an intermediate list. Note that all I've done is
remove the [ and ] - that's because a genexp must be surrounded by
parentheses, but *any* parentheses will do - for example, the
parentheses surrounding the parameters in a function call.
Tim Delaney
More information about the Python-list
mailing list