DEV Community

Timothy Cummins
Timothy Cummins

Posted on

Help: Reverse Dict

Introduction to the Problem

In my second week of holiday spirit I decided to continue my friend with his adventures in Python. In the most recent problem he was working on it gave him a dictionary of English words and their translation in Spanish and wanted him to create a program to inverse them. The requirement given to him were:

1) Raise an Exception for the error if something besides a dictionary is passed through the function

2) Return the reversed dictionary using a Zip function if a dictionary is passed through the function

So here is a step by step with some instruction about how I went through the problem.

Making Sure a Dictionary is Passed Through

So when I read this problem the first thing I thought to myself is that we are going to need a to define a function of course, but also that we should use an 'if' statement to give our function two options. So initially I typed up the following:

def invdict(D):
    if D is dict():
        print("item is dictionary")
    else:
        print("item is not a dictionary")
Enter fullscreen mode Exit fullscreen mode

Though when I tried to run the following dictionary I created I ended up receiving a response that the my dictionary was not a dictionary.

thisdict = {
    "dog": "perro",
    "cat": "gato",
    "chicken": "pollo",
    "chicken": "pollo"
    }
Enter fullscreen mode Exit fullscreen mode

This was because what I had typed above was comparing the dictionary I had created to dict() which is any empty dictionary, therefore they were not the same and in turn my statement was false. Noticing my mistake and thinking back on what I had learned in the past I remembered there was a built in function that would return True or False if an object was the specified type, isinstance(). Which worked!

def invdict(D):
    if isinstance(D,dict):
        print("item is dictionary")
    else:
        print("item is not a dictionary")
Enter fullscreen mode Exit fullscreen mode

Now we just needed to reverse our dictionary.

Reversing the Dictionary

I want to start out by saying there are a couple of ways to reverse a dictionary. Personally my first thought would be to go to a comprehension method by using something like dict((v, k) for k, v in D.items()) but as I said in the beginning this problem specified using a zip method. So to do that what we will have to do is actually pretty simple. Since the dictionary itself lets us call upon the keys and values separately as lists, all we need to do is tell python that we will want the result to be a dictionary using dict(), then to create that dictionary we will need connect two lists zip() and finally we need to provide those lists D.values() and D.keys(). So all together we have dict(zip(D.values(), D.keys())).

So putting everything together our output will look like:

def invdict(D):
    if isinstance(D,dict):
        return dict(zip(D.values(), D.keys()))
    else:
        raise Exception('This should be a dictionary')
Enter fullscreen mode Exit fullscreen mode

Conclusion

First of all I want to say that I hope if someone is using this for school work, I hope you at least read through this to help you understand what each piece is doing. Secondly I would like to announce that since I have finished the pleasantries of the holidays I look forward to tackling some more complex Machine Learning concepts in the upcoming weeks.

Happy Holidays!!!

Top comments (0)