Reverse Dictionary Data Structure

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

A dictionary is a collection of key-value pairs, where each key is unique. In Python, dictionaries are widely used to store and retrieve data efficiently. However, sometimes we need to invert a dictionary, i.e., swap the keys and values. This can be useful in many scenarios, such as searching for a key based on its value. In this challenge, you will write a Python function to invert a dictionary.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") subgraph Lab Skills python/comments -.-> lab-13665{{"`Reverse Dictionary Data Structure`"}} python/for_loops -.-> lab-13665{{"`Reverse Dictionary Data Structure`"}} python/dictionaries -.-> lab-13665{{"`Reverse Dictionary Data Structure`"}} python/function_definition -.-> lab-13665{{"`Reverse Dictionary Data Structure`"}} end

Invert a Dictionary

Write a Python function called invert_dictionary(obj) that takes a dictionary obj as an argument and returns a new dictionary with the keys and values inverted. The input dictionary obj will have unique hashable values. The output dictionary should have the same keys as the input dictionary, but the values should be the keys from the input dictionary.

You should use dictionary.items() in combination with a list comprehension to create the new dictionary.

def invert_dictionary(obj):
  return { value: key for key, value in obj.items() }
ages = {
  'Peter': 10,
  'Isabel': 11,
  'Anna': 9,
}
invert_dictionary(ages) ## { 10: 'Peter', 11: 'Isabel', 9: 'Anna' }

Summary

In this challenge, you learned how to invert a dictionary in Python. You used dictionary.items() in combination with a list comprehension to create a new dictionary with the values and keys inverted. This can be useful in many scenarios, such as searching for a key based on its value.

Other Python Tutorials you may like