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

 

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

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


πŸ“ Exercise 6-9

Task:
Make a dictionary called favorite_places .
Think of three names to use as keys in the dictionary, and store one to three favorite places for each person .
To make this exercise a bit more interesting, ask some friends to name a few of their favorite places . Loop through the dictionary, and print each person’s name and their favorite places

✅ Solution Code:


favorite_places = {
    "john": ["new york", "paris", "rome"],
    "jane": ["tokyo", "sydney"],
    "bob": ["barcelona", "amsterdam", "berlin"]
}

for name , places in favorite_places.items():
    print(f"Favourite Place Of {name} Are ")
    for place in places:
        print(place)
    print("------------------")

🧠 Code Explanation:

This Python code demonstrates how to use a dictionary to store multiple favorite places 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 places:

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

    • "john": ["new york", "paris", "rome"]
    • "jane": ["tokyo", "sydney"]
    • "bob": ["barcelona", "amsterdam", "berlin"]
  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 places represents the value (list of favorite places).

  3. Iterate through the list of places:

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

  4. Display results:

    For each person, their name and favorite places 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 Place Of john Are 
new york
paris
rome
------------------
Favourite Place Of jane Are 
tokyo
sydney
------------------
Favourite Place Of bob Are  
barcelona
amsterdam
berlin
------------------

πŸ“š 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