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

 

πŸ“˜ Python Crash Course – Chapter 6: Dictionaries – Exercise 6-10 Solution

Welcome to another solution from Python Crash Course by Eric Matthes.


πŸ“ Exercise 6-10

Task:
Modify your program from Exercise 6-2 so each person can have more than one favorite number . Then print each person’s name along with their favorite numbers

✅ Solution Code:


fav_no = {
    "Tony" : [10,5,9],
    "hulk" : [6,78,10,56],
    "Hwakeye" : [100,1],
    "Natasha" : [49,45,1000,0000],
    "Thanos" : [50]
}

for name , num in fav_no.items():
    print(f"Favourite Number Of {name}: ")
    for number in num:
        print(number)
    print("------------------")

🧠 Code Explanation:

This Python code demonstrates how to use a dictionary to store multiple favorite numbers for different people and how to iterate through the dictionary to display the data. Here's how it works:

  1. Create a dictionary of favorite numbers:

    The variable fav_no is assigned a dictionary where the keys are names of people, and the values are lists of their favorite numbers. For example:

    • "Tony": [10, 5, 9]
    • "hulk": [6, 78, 10, 56]
    • "Hwakeye": [100, 1]
    • "Natasha": [49, 45, 1000, 0000]
    • "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 (list of favorite numbers).

  3. Iterate through the list of numbers:

    For each person, a nested for loop iterates through their list of favorite numbers. Each number is displayed one by one.

  4. Display results:

    For each person, their name and favorite numbers are displayed, followed by a separator line for better readability.

This code demonstrates how to use dictionaries to store lists as values and how to iterate through nested data structures to display the information in an organized manner.

πŸ” Output:


Favourite Number Of Tony: 
10
5
9
------------------
Favourite Number Of hulk:    
6
78
10
56
------------------
Favourite Number Of Hwakeye: 
100
1
------------------
Favourite Number Of Natasha: 
49
45
1000
0
------------------
Favourite Number Of Thanos:
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

“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

πŸ“Œ Follow Us And Stay Updated For Daily Updates

Comments