I teach computer science to undergrads and write for The Renegade Coder. I'm most likely taking care of my daughter, watching the Penguins, or reading manga.
Location
Columbus, Ohio
Education
B.S. in CE from CWRU 2016; M.S. in CSE from OSU 2020; PhD in EED from OSU 2024
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.
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
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
You can also use zip if you don't mind non-unique values being merged:
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.
Yeah, the dict comprehension is the clearest way of doing this.
zipis mildly faster but I agree calling keys and values separately is slightly offputting: