π 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:
-
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]
-
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 (list of favorite numbers). -
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. -
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
πTrending Topics
π 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
π Follow Us And Stay Updated For Daily Updates
Comments
Post a Comment