📘 Python Crash Course – Chapter 6: Dictionaries – Exercise 6-2 Solution
Welcome to another solution from Python Crash Course by Eric Matthes.
📝 Exercise 6-2
Task:
Use a dictionary to store people’s favorite numbers .
Think of five names, and use them as keys in your dictionary . Think of a favorite
number for each person, and store each as a value in your dictionary .
Print
each person’s name and their favorite number . For even more fun, poll a few
friends and get some actual data for your program
✅ Solution Code:
fav_no = {
"Tony" : 10,
"hulk" : 6,
"Hwakeye" : 100,
"Natasha" : 49,
"Thanos" : 50
}
# we can use all the methods of exercise 6.1
for name , num in fav_no.items():
print(f" Favourite Number Of {name} is {num}")
🧠 Code Explanation:
This Python code demonstrates how to use a dictionary to store and display people's favorite numbers. Here's how it works:
-
Create a dictionary:
The variable
fav_no
is assigned a dictionary where the keys are names of people, and the values are their favorite numbers. For example:"Tony": 10
"Hulk": 6
"Hwakeye": 100
"Natasha": 49
"Thanos": 50
-
Iterate through the dictionary:
The
items()
method is used to retrieve all key-value pairs from the dictionary. Afor
loop iterates through these pairs, wherename
represents the key (person's name) andnum
represents the value (favorite number). -
Display the data:
For each key-value pair, a message is displayed showing the person's name and their favorite number.
This code demonstrates how to use dictionaries to store and retrieve related data, such as names and corresponding favorite numbers, and how to iterate through the dictionary to display its contents.
🔍 Output:
Favourite Number Of Tony is 10
Favourite Number Of hulk is 6
Favourite Number Of Hwakeye is 100
Favourite Number Of Natasha is 49
Favourite Number Of Thanos is 50
📚 Related Exercises from Chapter 6:
- ➤ Exercise 6-1 | Person
- ➤ Exercise 6-2 | Favorite Numbers
- ➤ Exercise 6-3 | Glossary
- ➤ Exercise 6-4 | Glossary 2
- ➤ Exercise 6-5 | Rivers
- ➤ Exercise 6-6 | Polling
- ➤ Exercise 6-7 | People
- ➤ Exercise 6-8 | Pets
- ➤ Exercise 6-9 | Favorite Places
- ➤ Exercise 6-10 | Favorite Numbers
- ➤ Exercise 6-11 | Cities
- ➤ Exercise 6-12 | Extensions
🔗 Connect With Us:
“In the world of code, Python is the language of simplicity, where logic meets creativity, and every line brings us closer to our goals.”
— Only Python
📌 Tags: #Python #PythonCrashCourse #CodingForBeginners #LearnPython #PythonProjects #PythonTips