Hacker News new | ask | show | jobs
by lqdc13 4480 days ago
zip to unzip a dict is a very slow approach to do it

Instead of

    mi = dict(zip(m.values(), m.keys()))
Do

    mi = {v: k for (k, v) in m.iteritems()}
2 comments

When did support for dictionary comprehensions make it into 2.x? I could've sworn it didn't used to work, but I just tried it in the shell and sure enough, it does in 2.7.3.
Wow I didn't know that! I was always doing something like this

    mi = dict((v,k) for k,v in m.iteritems())
more importantly it's wrong - the iteration order of .values() and .keys() is not guaranteed to be consistent
The order of items in the dictionary isn't stable, but the order of .keys() is guaranteed to be the same as the order of .values() (as long as you don't modify the dict in between calling one then the other).

http://docs.python.org/2/library/stdtypes.html#dict.items