TL;DR If you want to generate a python dict with the key and value reversed, the following is the fastest.
d = dict(zip(list('abc'), range(3))) #Generate a suitable dictionary as an example
d2 = dict(zip(d.values(), d.keys())) #Reverse
When writing python, you may want to generate the key and value of an existing dict in reverse. For example
{'a': 0, 'b': 1, 'c': 2}
Against
{0: 'a', 1: 'b', 2: 'c'}
is. So I tried some ways to get the reverse version fastest.
d = dict(zip([f'key{i}' for i in range(10000)], range(10000))) #Appropriate dictionary
%%timeit
d2 = dict()
for k in d:
d2[d[k]] = k
Result: 1.09 ms ± 57.7 µs per loop (mean ± std. Dev. Of 7 runs, 1000 loops each)
%timeit dict(zip(d.values(), d.keys()))
Result: 525 µs ± 21.7 µs per loop (mean ± std. Dev. Of 7 runs, 1000 loops each)
%timeit {v:k for k,v in d.items()}
Result: 661 µs ± 23 µs per loop (mean ± std. Dev. Of 7 runs, 1000 loops each)
As a result, combining the value and the key with 2.zip became the fastest. The internal behavior of python is unstudied and unclear, but I feel that the for loop is working. It has been pointed out in various places that the python for loop is slow because the type check is entered each time.
However, since it is not so different from the dictionary comprehension that is the second place, it may be good to use 3. in consideration of the deep nesting of (), which reduces readability.
that's all.
Recommended Posts