Inverting a dictionary in python

Hi, friends in this session we are going to learn how to invert a dictionary in Python. Python provides a class dictionary which is usually defined as a collection of key value pairs. Inverting a dictionary in python means we are going to interchange the key and value in the dictionary. First, let us learn about a dictionary

Storing data using Dictionary

Sometimes we may have the need of storing key value pairs. In Python, we have dictionaries for this purpose.  Without dictionaries, it is a bit difficult to store key value pairs. Suppose you have to store the number of copies of each book you have. So, here names of the books are keys and the number of copies each has is the value associated with each key. It is simple to say but think of any other ways to store them. You can use a set with a number of 2 values tuples in them. In which one is the book’s name and the other is the number of copies. And we also have another way that is you can use a list. In which consecutive fields store the book name and the number of copies of the book.

One thing you can say for sure is that in all the alternative ways of storing key value pairs you find complexity.  That is why we use dictionaries. To learn more about the data collection dictionaries go through this link   Creation, Addition, Removal, and Modification of Dictionary in Python

That is all about the data collection dictionaries. Now let’s get into our task of inverting a dictionary. One thing you should never forget about dictionaries is that dictionaries or immutable. Though you can change the value of a key, you can’t modify the keys of a dictionary. You can only just add them.

How to invert a dictionary in Python

As seen earlier you can use a dictionary to store the name of books you have and the copies of the books you have.  Inverting a dictionary means you have to make the number of copies as key and the names of books available in that number of copies given by key as value. For example, consider this dictionary that you should have initialized earlier

books_copies={'Programming in C':3,'Database management systems':1,'Computer Organization':2,'Operations Research':2}

After inverting we should have a dictionary like for key ‘2’ the value should be a list with computer organization and operations research. Lets see the program that does the conversion for us.

//initializing an empty dictionary for inverting
for book, count in books_copies.items():
//iterative step for each key value pair in books_copies dictionary
    if count in inverse:
        inverse[count] = [book]


The output of this program looks like

{3:['Programming in C'],1:['Database management systems'],
2:['Computer Organization','Operations Research']}

That’s all about inverting a dictionary in Python. I hope you like this session.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *