How to reverse dict python

How to reverse dict python

Reversible dictionary for python

I’d like to store some data in Python in a similar form to a dictionary: <1:'a', 2:'b'>. Every value will be unique, not just among other values, but among keys too.

Is there a simple data structure that I can use to get the corresponding object no matter if I ask using the ‘key’ or the ‘value’? For example:

The ‘keys’ are standard python ints, an the values are short ( Follow

7 Answers 7

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

If your keys and values are non-overlapping, one obvious approach is to simply store them in the same dict. ie:

This should only involve one lookup, though may not save you much in memory (you still have twice the number of dict entries after all). Note however that neither this nor your original will use up twice as much space: the dict only takes up space for the references (effectively pointers), plus an overallocation overhead. The space taken up by your data itself will not be repeated twice since the same objects are pointed to.

Of course, if all values and keys are unique, couldn’t you just use a single dictionary, and insert both key:value and value:key initially?

In The Art of Computer Programming, Vokume 3 Knuth has a section on lookups of secondary keys. For purposes of your question, the value could be considered the secondary key.

The first suggestion is to do what you have done: make an efficient index of the keys by value.

The second suggestion is to setup a large btree that is a composite index of the clustered data, where the branch nodes contain values and the leaves contain the key data and pointers to the larger record (if there is one.)

If the data is geometric (as yours appears to be) there are things called post-office trees. It can answer questions like, what is the nearest object to point x. A few examples are here: http://simsearch.yury.name/russir/01nncourse-hand.pdf Another simple option for this kind of query is the quadtree and the k-d tree. http://en.wikipedia.org/wiki/Quadtree

Another final option is combinatorial hashing, where you combine the key and value into a special kind of hash that lets you do efficient lookups on the hash, even when you don’t have both values. I couldn’t find a good combinatorial hash explanation online, but it is in TAoCP, Volume 3 Second Edition on page 573.

Granted, for some of these you may have to write your own code. But if memory or performance is really key, you might want to take the time.

Reverse a Dictionary in Python

This article demonstrates different methods to invert a dictionary in Python.

Reversing a dictionary is different from reversing a list, it means to invert or switch the key and value elements of the dictionary, essentially swapping them for whatever purpose the developer might use it for.

Use items() to Reverse a Dictionary in Python

Python dictionaries have a built-in function called items() which returns an iterable object that will display the dictionaries’ key-value pairs in the form of a tuple.

Printing a dictionary using items() will output an iterable list of tuple values that we can manipulate using the for loop for dictionaries.

Please enable JavaScript

Reverse the key-value pairs by looping the result of items() and switching the key and the value.

The k and v in the for loop stands for key and value respectively. v: k are the placeholders for the key and value in each iteration, although we set the previous value v as the new key and the previous key k as the new value.

The key and the value elements are now reversed in the output.

Same Valued Keys in a Reversed Dictionary

Another example scenario when inverting a dictionary is if there are multiple keys or values with the same value. This is a more likely scenario to invert a dictionary.

For example, a dictionary of people’s favorite animals.

If the dictionary is inverted using the above code, the output would not be as you’d expect.

Here, 2 elements from the original dictionary are missing because every time a key or a value repeats in the loop, the existing record will be overwritten.

The dictionary contains 3 people with the value pair Dog but only James was copied because this was the last record with the value of Dog and has overwritten the 2 other dictionary items.

To solve this problem, we would have to store the values in a list so they would be assigned to a single key.

The complete example code:

Use collections.defaultdict() to Reverse a Dictionary in Python

The module collections has a function defaultdict() which can manipulate the values in a dictionary in Python.

defaultdict() mainly is used for creating default values of non-existent keys. If you access a non-existent key, it can declare a default value for it, even if it doesn’t exist.

This function is useful for our case because we want to instantiate a new dictionary with values that are of a list data type.

First, initialize the new dictionary using defaultdict()

Next, use the list comprehension for inversion and store the inverted values into the new dictionary.

John, Jenny, and James now are on the same list with the key Dog instead of the other elements being overwritten by the last element that had Dog as their value.

The complete example code:

In summary, use items() to loop over the dictionary and invert the keys and values. If by any chance your data set is likely to have duplicates, then make sure to convert the values into a list by using defaultdict() and manipulate it in a way that the values of the dictionary will append into the list instead of replacing the existing values.

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

How to reverse dict python. Смотреть фото How to reverse dict python. Смотреть картинку How to reverse dict python. Картинка про How to reverse dict python. Фото How to reverse dict python

Welcome to the start of the How to Python series. In this series, I’m putting together several articles for small Python problems that can be solved in a few lines of code. This series is inspired by the everyday Google searches I make to solve my own problems at work. To get started, I’ve decided to kick off the series by writing an article on how to invert a dictionary.

In short, one of the best ways to invert a dictionary in Python is to use a for loop in conjunction with the setdefault method of dictionaries to store duplicate keys in a list. If that’s not an issue for you, a dictionary comprehension works great: . As always, we’ll take a look at other solutions as well.

Table of Contents

Video Summary

In order to supplement my articles, I’ve been slowly but surely launching accompanying videos. As a matter of fact, this is just my second YouTube video, so show it some love!

In it, I share all of the same solutions to the dictionary inversion problem that you’ll find in this article. Of course, the advantage of a video is that you can see it all live with a bit of my own commentary. If you want to jump to a specific part of the video, I have the timestamps setup in the description.

Problem Introduction

Recently, I was working on a Python project where I needed to invert a dictionary. For all you Boku no Hero AcademiaHow to reverse dict python. Смотреть фото How to reverse dict python. Смотреть картинку How to reverse dict python. Картинка про How to reverse dict python. Фото How to reverse dict python (BNHA) fans out there, I basically wanted to be able to do the following:

In this scenario, we have a dictionary of characters from BNHA mapped to their quirks, and we want to convert that to a dictionary of quirks mapped to the characters that have them.

Unfortunately, the original dictionary has non-unique values, so flipping the dictionary would result in a loss of keys. Instead, we want to accumulate a list of keys for each non-unique value while performing the inversion. As it turns out, this is pretty easy to do.

Note: If you’re looking to perform a reverse dictionary lookup (i.e. get a key given a value), I have a whole other article for that. Otherwise, let’s move on!

Solutions

If we want to invert a dictionary, we have several options. From comprehensions to loops, we’ll take a look at all the practical solutions.

Invert a Dictionary with Map and Reversed

Let’s kick off our series of options with one of the more succinct options:

Here, we use the map function which applies the reversed function to all the items in the dictionary. Then, we take the map object and convert it into a dictionary. The result looks something like the following:

Of course, if we want to make sure we don’t lose Midoriya, we shouldn’t use this method. Otherwise, this would be a perfect solution.

Invert a Dictionary with Zip

According to Capi EtherielHow to reverse dict python. Смотреть фото How to reverse dict python. Смотреть картинку How to reverse dict python. Картинка про How to reverse dict python. Фото How to reverse dict python, there’s yet another way to reverse a dictionary with unique values. Specifically, they mentioned zipping the keys and values in their reverse order and converting the output to a dictionary:

When I first saw this solution, I was a bit skeptical that it would actually work. After all, until Python 3.7, dictionaries had no orderingHow to reverse dict python. Смотреть фото How to reverse dict python. Смотреть картинку How to reverse dict python. Картинка про How to reverse dict python. Фото How to reverse dict python. In other words, I felt like it wasn’t clear that values() and keys() would return lists that actually lined up. That’s why we typically use a method like items() to ensure we get the keys and values together as pairs.

Well, I kept digging. Apparently, keys() and values() always correspond assuming no changes to the dictionary between calls—at least according to a few folks on Stack OverflowHow to reverse dict python. Смотреть фото How to reverse dict python. Смотреть картинку How to reverse dict python. Картинка про How to reverse dict python. Фото How to reverse dict python. Of course, be aware that we’ll lose Midoriya with this solution as well:

In other words, if you have unique values, this might be the option for you.

Invert a Dictionary with a Comprehension

In Python 2.7 and above, we can use a dictionary comprehension to invert a dictionary. Unfortunately, it falls prey to the same issue mentioned before, but it gets the job done for unique values:

Once again, here’s the result of inverting our example dictionary:

As we can see, we lose one of our keys. Perhaps there is a better way to invert a dictionary.

Invert a Dictionary with Defaultdict

Luckily, there is another way! Thanks to our friend, Niels van Galen LastHow to reverse dict python. Смотреть фото How to reverse dict python. Смотреть картинку How to reverse dict python. Картинка про How to reverse dict python. Фото How to reverse dict python, we can accomplish exactly what we need in three lines of code:

All of that said, this solution is considered bad practiceHow to reverse dict python. Смотреть фото How to reverse dict python. Смотреть картинку How to reverse dict python. Картинка про How to reverse dict python. Фото How to reverse dict python (also, I’d love a source better than Stack Overflow). After all, we are not using the dictionary comprehension as intended. It’s meant to generate a dictionary, but we’re using it to modify an external dictionary.

Invert a Dictionary with a For Loop

Another way to invert a dictionary is to use a for loop. This allows us to iterate over the set of mappings and properly build the new mappings by hand. Take a look:

With this method, we can invert a dictionary while preserving all of our original keys. Let’s take a look at what would happen if we ran this code snippet:

Great! We have exactly what we need, but what happens if we want to return this dictionary to its original form?

Revert the Inversion

In the basic case where all keys and values are unique, we can revert a dictionary back to its original mapping using the same dictionary comprehension we’ve already covered:

Unfortunately, this doesn’t work out with a dictionary that maps keys to lists. That’s because lists in Python are unhashable types. In other words, Python doesn’t allow lists to be keys in dictionaries because lists are not immutableHow to reverse dict python. Смотреть фото How to reverse dict python. Смотреть картинку How to reverse dict python. Картинка про How to reverse dict python. Фото How to reverse dict python.

Fortunately, it’s easier to revert our dictionary than it was to invert it in the first place. We can use the following dictionary comprehension:

As we can see, we make a new key-value pair for every single value in each list using this double loop structure.

Performance

Recently, I thought it would be fun to start adding performance information to these articles. In particular, I’m interested in comparing these solutions by their run time. To do that, we’ll use the timeit library. Before we can run our metrics, we’ll need to setup our solutions in strings:

With our strings in hand, we can run our test:

As it turns out, the dictionary comprehension is very fast. However, be aware that it can’t handle non-unique values. If that’s not a constraint, then go with the fast solution. Otherwise, it doesn’t really matter which method you choose.

Also, for reference, I ran this on my Windows 10 desktop with Python 3.7.3. If you’re interested in learning more about this performance testing process, I have an article for that.

A Little Recap

Using the methods above, we can invert just about any dictionary.

Just about every other type of dictionary transformation is out of the scope of this tutorial. However, if you have any specific questions, feel free to reach out in the comments.

While you’re here, you might be interested in these articles as well:

If you’re not sure where to start, I recommend my list of Python Code Snippets for Everyday Problems. Alternatively, you can get the latest articles sent to your inbox by becoming a memberHow to reverse dict python. Смотреть фото How to reverse dict python. Смотреть картинку How to reverse dict python. Картинка про How to reverse dict python. Фото How to reverse dict python or subscribing to the newsletter.

While you’re here, check out some of these related BNHA products on Amazon (ad).

Thanks again for sticking around!

How to Python (41 Articles)—Series Navigation

The How to Python tutorial series strays from the usual in-depth coding articles by exploring byte-sized problems in Python. In this series, students will dive into unique topics such as How to Invert a Dictionary, How to Sum Elements of Two Lists, and How to Check if a File Exists.

Each problem is explored from the naive approach to the ideal solution. Occasionally, there’ll be some just-for-fun solutions too. At the end of every article, you’ll find a recap full of code snippets for your own use. Don’t be afraid to take what you need!

If you’re not sure where to start, I recommend checking out our list of Python Code Snippets for Everyday Problems. In addition, you can find some of the snippets in a Jupyter notebook format on GitHubHow to reverse dict python. Смотреть фото How to reverse dict python. Смотреть картинку How to reverse dict python. Картинка про How to reverse dict python. Фото How to reverse dict python,

If you have a problem of your own, feel free to ask. Someone else probably has the same problem. Enjoy How to Python!

How to reverse order of keys in python dict?

This is my code :

but I want it to show:

so, what can I do?

11 Answers 11

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

The order keys are iterated in is arbitrary. It was only a coincidence that they were in sorted order.

Since Python 3.7 dicts preserve order, which means you can do this now:

Since Python 3.8 the built-in reversed() accepts dicts as well, thus you can use:

How to reverse dict python. Смотреть фото How to reverse dict python. Смотреть картинку How to reverse dict python. Картинка про How to reverse dict python. Фото How to reverse dict python

Dictionaries are unordered so you cannot reverse them. The order of the current output is arbitrary.

That said, you can order the keys of course:

but this gives you the reverse order of the sorted keys, not necessarily the reverse order of the keys how they have been added. I.e. it won’t give you 1 0 3 if your dictionary was:

How to reverse dict python. Смотреть фото How to reverse dict python. Смотреть картинку How to reverse dict python. Картинка про How to reverse dict python. Фото How to reverse dict python

How to reverse dict python. Смотреть фото How to reverse dict python. Смотреть картинку How to reverse dict python. Картинка про How to reverse dict python. Фото How to reverse dict python

Python dict is not ordered in 2.x. But there’s an ordered dict implementation in 3.1.

Python dictionaries don’t have any ‘order’ associated with them. It’s merely a ‘coincidence’ that the dict is printing the same order. There are no guarantees that items in a dictionary with come out in any order.

If you want to deal with ordering you’ll need to convert the dictionary to a list.

Now you can sort the list as normal, e.g., a.sort() and reverse it as well, e.g., a.reverse()

In Python 3.6, which I am using, I reversed the order of keys with their respective values with the help of function update.

How to reverse python dictionary?

The reversed() function accepts the parameter sequence and returns the sequence in reverse order.

The map() method applies a given function on each item of iterable and the iterable can be a list, tuple, set, or frozen set.

It returns results according to the iterable.

The zip() function accepts an iterable object and returns an iterable object and the elements from the passed iterator are paired together. It returns a list of the iterable.

Example: Reverse a dictionary using Comprehension

The comprehension concept is also applicable to the dictionary. This method is easy, it just exchanges key and value pairs.

Once we run the code, it shows the following result.

Example: Reverse a dictionary using reversed() and map() function.

The below example shows how to reverse the dictionary using the map() method and reversed() function.

In the above example, first, we defined the dictionary with key-value pairs.

Next, we are using the map() method to reverse the dictionary. Here, in the parameter section, we gave the function as reversed and iterable as dict_1.items.

We are storing the map() method output in the variable output.

In the next step, we are converting them again into the dictionary data type.

Once we run the code, it shows the following result.

Example: Reverse a dictionary using the zip() function.

The below example shows how to reverse a dictionary using the zip() function.

In the above example, we defined the dictionary with key-value pairs. Using the values() method, we are getting the values from the dictionary and that will store in the variable get_values.

Using the keys() method, we are getting the keys from the dictionary and that will store in the variable get_keys.

In the next step, we are passing a sequence of values and keys to the zip() function. The zip() function accepts these sequences and the elements present in the sequence will be paired together.

Next, we are converting the zip() function output to the dictionary.

Once we run the code, it shows the following result.

Dictionary: <100: 'python', 200: 'Java', 300: 'Ruby', 400: 'C', 500: 'C++', 600: 'R'>
——Getting values from dictionary——
Values from dictionary: dict_values([‘python’, ‘Java’, ‘Ruby’, ‘C’, ‘C++’, ‘R’])
——Getting keys from dictionary——
Values from dictionary: dict_keys([100, 200, 300, 400, 500, 600])
Using the zip() function
Reversed Dictiionary:

Example: Reverse a dictionary without built-in functions.

The below example shows how to reverse a dictionary using for loop.

Once we run the code, it shows the following result.

Conclusion

In this tutorial, we learned to reverse the python dictionaries using the comprehension method, reversed(), map(), zip() functions, and using the for loop.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *