0
0
Pythonprogramming~15 mins

Inverting a dictionary in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Inverting a dictionary
๐Ÿ“– Scenario: Imagine you have a dictionary that stores the names of fruits as keys and their colors as values. You want to create a new dictionary that flips this information, so the colors become the keys and the fruits become the values.
๐ŸŽฏ Goal: Build a Python program that inverts a dictionary by swapping its keys and values.
๐Ÿ“‹ What You'll Learn
Create a dictionary with fruit names as keys and their colors as values
Create a variable to hold the inverted dictionary
Use a dictionary comprehension to invert the original dictionary
Print the inverted dictionary
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Inverting dictionaries is useful when you want to look up information in reverse, like finding all fruits by their color instead of the other way around.
๐Ÿ’ผ Career
Understanding how to manipulate dictionaries and use comprehensions is important for data processing, software development, and many programming tasks.
Progress0 / 4 steps
1
Create the original dictionary
Create a dictionary called fruits with these exact entries: 'apple': 'red', 'banana': 'yellow', 'grape': 'purple', 'orange': 'orange', 'lemon': 'yellow'.
Python
Need a hint?

Use curly braces {} to create the dictionary and separate each key-value pair with a comma.

2
Create an empty dictionary for the inverted data
Create an empty dictionary called inverted to hold the inverted fruit-color pairs.
Python
Need a hint?

Use empty curly braces {} to create an empty dictionary.

3
Invert the dictionary using dictionary comprehension
Use a dictionary comprehension to create the inverted dictionary by swapping keys and values from fruits. Use color and fruit as the variable names in the comprehension.
Python
Need a hint?

Use {key: value for key, value in dictionary.items()} format, swapping the key and value positions.

4
Print the inverted dictionary
Write a print statement to display the inverted dictionary.
Python
Need a hint?

Use print(inverted) to show the result.