Inverse of dict(zip(x,y))

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Mar 4 22:38:34 EST 2009


On Wed, 04 Mar 2009 08:00:14 -0800, Paul McGuire wrote:

> On Mar 4, 5:33 am, Lie Ryan <lie.1... at gmail.com> wrote:
>> Andre Engels wrote:
>> > y = d.values() might also work, but I am not sure whether d.keys()
>> > and d.values() are guaranteed to use the same order.
>>
>> If they were called immediately after each other I think they should,
>> but better not rely on it.
> 
> Also, it offends my efficiency/performance sensibilities to use two
> separate calls to iterate over the dict twice, when there is a perfectly
> good equivalent that is just as readable and iterates only once.

Sure, but if you want two lists, as the OP asked for, then you have to 
iterate over it twice either way:

# method 1:
keys = dict.keys()
values = dict.values()

# method 2:
keys, values = zip(*dict.items())

First you iterate over the dict to get the items, then you iterate over 
the items to split into two lists. Anyone want to take bets on which is 
faster?


>>> from timeit import Timer
>>>
>>> d = {'a':1, 'b':2, 'c':3, 'z':26}
>>> Timer('d.keys();d.values()', 'from __main__ import d').repeat()
[1.1103789806365967, 0.90148496627807617, 0.9004051685333252]
>>> Timer('zip(*d.items())', 'from __main__ import d').repeat()
[2.1786351203918457, 2.0767219066619873, 2.076124906539917]

For a small dict, the zip solution is about twice as slow. What about for 
a bigger dict?

>>> D = dict((n, n*2+1) for n in xrange(-20, 1000000))
>>> Timer('D.keys();D.values()', \
... 'from __main__ import D').repeat(number=100)
[9.2809889316558838, 9.150738000869751, 9.2292399406433105]
>>> Timer('zip(*D.items())', \
... 'from __main__ import D').repeat(number=100)
[63.850389957427979, 55.749162912368774, 61.448837041854858]



Well, I think this is clear evidence that the zip solution is a 
pessimation, not an optimization.

That's what I love about Python -- my intuition about what code is faster 
is so often wrong!

[only half sarcastic...]

-- 
Steven



More information about the Python-list mailing list