DEV Community

loading...

Discussion on: How to Invert a Dictionary in Python: Comprehensions, Defaultdict, and More

Collapse
mikedh profile image
Michael Dawson-Haggerty

You can also use zip if you don't mind non-unique values being merged:

In [11]: d = {'hi': 'stuff'}

In [12]: dict(zip(d.values(), d.keys()))
Out[12]: {'stuff': 'hi'}
Collapse
renegadecoder94 profile image
Jeremy Grifski Author

Good point! I always hesitate with this solution because it’s not immediately clear that the two collections would maintain their order. I know they do, but it still bothers me.

Collapse
mikedh profile image
Michael Dawson-Haggerty

Yeah, the dict comprehension is the clearest way of doing this. zip is mildly faster but I agree calling keys and values separately is slightly offputting:

In [7]: d = {a: b for a,b in (np.random.random((100000, 2)) * 1e6).astype(int)}

In [8]: %timeit {v: k for k, v in d.items()}
100 loops, best of 3: 12.3 ms per loop

In [9]: %timeit dict(zip(d.values(), d.keys()))
100 loops, best of 3: 10.8 ms per loop