What is the fastest way to create a reverse dictionary in python?

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

Main subject

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.

Preparation

d = dict(zip([f'key{i}' for i in range(10000)], range(10000))) #Appropriate dictionary

1. for loop

%%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)

2. Zip the value and key together

%timeit dict(zip(d.values(), d.keys()))

Result: 525 µs ± 21.7 µs per loop (mean ± std. Dev. Of 7 runs, 1000 loops each)

3. Dictionary comprehension

%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)

result

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

What is the fastest way to create a reverse dictionary in python?
Create a dictionary in Python
Probably the easiest way to create a pdf with Python3
[Introduction to Python] What is the recommended way to install pip, a package management system?
What is "mahjong" in the Python library? ??
Hash in Perl is a dictionary in Python
What to do when the value type is ambiguous in Python?
The fastest way for beginners to master Python
What to do if there is a decimal in python json .dumps
[Python] What is a formal argument? How to set the initial value
[Introduction to Python] What is the difference between a list and a tuple?
I want to create a window in Python
What is wheezy in the Docker Python image?
How to create a JSON file in Python
A clever way to time processing in Python
Excel X Python The fastest way to work
Check if the string is a number in python
Create a plugin to run Python Doctest in Vim (2)
Create a plugin to run Python Doctest in Vim (1)
What does the last () in a function mean in Python?
Create a function in Python
What is a python map?
Create a python script to check if the link at the specified URL is valid 2
Create a python script to check if the link at the specified URL is valid
What to do if the progress bar is not displayed in tqdm of python
How to check in Python if one of the elements of a list is in another list
[Mac] A super-easy way to execute system commands in Python and output the results
[python] How to check if the Key exists in the dictionary
Create a local scope in Python without polluting the namespace
How to use the __call__ method in a Python class
Change the standard output destination to a file in Python
A simple way to avoid multiple for loops in Python
A standard way to develop and distribute packages in Python
How to get the last (last) value in a list in Python
Create a tool to check scraping rules (robots.txt) in Python
Introducing a good way to manage DB connections in Python
[Python] What is a zip function?
[Python] What is a with statement?
Create a DI Container in Python
Get the value of a specific key up to the specified index in the dictionary list in Python
[Python] What is @? (About the decorator)
In the python command python points to python3.8
Create a binary file in Python
[python] What is the sorted key?
What seems to be a template of the standard input part of the competition pro in python3
I tried to create a Python script to get the value of a cell in Microsoft Excel
Create a Kubernetes Operator in Python
What is the python underscore (_) for?
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
5 Ways to Create a Python Chatbot
The fastest way to try EfficientNet
Create a random string in Python
An easy way to view the time taken in Python and a smarter way to improve it
An easy way to hit the Amazon Product API in Python
Play a sound in Python assuming that the keyboard is a piano keyboard
How to determine the existence of a selenium element in Python
[Introduction to Python] What is the most powerful programming language now?
What to do if you get a minus zero in Python
How to give and what the constraints option in scipy.optimize.minimize is
How to check the memory size of a variable in Python
Create a shell script to run the python file multiple times