Python tips: reverse a dictionary
In Python, if you want to reverse a dictionary ( dict ), i.e. swap the keys and values, there are three methods that can help you achieve that goal depending on your needs: Method 1 : makes use of dict comprehension , and the dict must contain unique values Method 2 : makes use of dict.get() , and the dict doesn't contain unique values Method 3 : makes use of map(reversed, iter) , and you want the reverse dict to preserve the type and order of the original dict (if for example it is an OrderedDict ) I provided code implementations for each methods that work for Python 2.7.x and 3+, and the embedded code can be executed directly from the blog post through JDoodle , an online compiler and editor for many other languages (68 in total such as C/C++, Java, Go, SQL). I also compiled the average running times of the different methods in a table at the end ( Method 1 with dict comprehension is the fastest! Spoiler alert: Click to reveal winning method ) The code used ...