Exercise 6-2 Solution Python Crash Course Chapter 6: Dictionaries

 

📘 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:

  1. 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
  2. Iterate through the dictionary:

    The items() method is used to retrieve all key-value pairs from the dictionary. A for loop iterates through these pairs, where name represents the key (person's name) and num represents the value (favorite number).

  3. 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:


🔗 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

Previous Post Next Post

Contact Form