DEV Community

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

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