Dictionary Exercises in Python

Working with dictionaries in Python can be enhanced through practice. Here are some exercises to help you solidify your understanding and improve your skills with dictionaries.

Exercise 1: Create and Print a Dictionary

Create a dictionary that stores information about a book: title, author, year, and genre. Print out each piece of information in a formatted manner.

Python

# Exercise 1: Create and print a dictionary
book = {
    "title": "To Kill a Mockingbird",
    "author": "Harper Lee",
    "year": 1960,
    "genre": "Fiction"
}

# Printing book information
print("Book Title:", book["title"])
print("Author:", book["author"])
print("Year:", book["year"])
print("Genre:", book["genre"])

Exercise 2: Modify and Update Dictionary Entries

Update the dictionary from Exercise 1 by adding the publisher and updating the genre. Then, print the updated dictionary.

Python

# Exercise 2: Modify and update dictionary entries
book["publisher"] = "J.B. Lippincott & Co."
book["genre"] = "Southern Gothic"

print(book)

Exercise 3: Remove an Entry from a Dictionary

Remove the "year" entry from the dictionary created in Exercise 2. Print the dictionary before and after the removal.

Python

# Exercise 3: Remove an entry from a dictionary
print("Before removal:")
print(book)

del book["year"]

print("After removal:")
print(book)

Exercise 4: Nested Dictionaries

Create a nested dictionary where you store information about multiple books. Each book should have its own dictionary containing title, author, and year. Print the entire nested dictionary.

Python

# Exercise 4: Nested dictionaries
library = {
    "book1": {
        "title": "1984",
        "author": "George Orwell",
        "year": 1949
    },
    "book2": {
        "title": "Pride and Prejudice",
        "author": "Jane Austen",
        "year": 1813
    },
    "book3": {
        "title": "The Great Gatsby",
        "author": "F. Scott Fitzgerald",
        "year": 1925
    }
}

print(library)

Exercise 5: Iterate Through a Nested Dictionary

Iterate through the nested dictionary from Exercise 4 to print each book's title, author, and year in a readable format.

Python

# Exercise 5: Iterate through a nested dictionary
for book_key, book_info in library.items():
    print(f"Title: {book_info["title"]}")
    print(f"Author: {book_info["author"]}")
    print(f"Year: {book_info["year"]}\n")