4 ms·
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()}
by lqdc13 13y 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()}
- mildtrepidation 13y agoWhen 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.
- maxerickson 13y ago2.7: http://legacy.python.org/dev/peps/pep-0274/ http://legacy.python.org/dev/peps/pep-0274/
- chingjun 13y agoWow I didn't know that! I was always doing something like this mi = dict((v,k) for k,v in m.iteritems())
- nerfhammer 13y agomore importantly it's wrong - the iteration order of .values() and .keys() is not guaranteed to be consistent
- davidwtbuxton 13y agoThe 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 http://docs.python.org/2/library/stdtypes.html#dict.items