Python - Dictionary Exercises: Your Friendly Guide to Mastering Dictionaries

Hello there, aspiring Python programmer! I'm thrilled to be your guide on this exciting journey into the world of Python dictionaries. As someone who's been teaching programming for years, I can tell you that dictionaries are like the Swiss Army knives of Python - incredibly versatile and useful. So, let's roll up our sleeves and dive in!

Python - Dictionary Exercises

What Are Dictionaries?

Before we jump into the exercises, let's quickly recap what dictionaries are. Imagine a magical book where you can instantly find any information just by thinking of a keyword. That's essentially what a Python dictionary is! It's a collection of key-value pairs, where each key acts as a unique identifier for its associated value.

Here's a simple example:

my_first_dict = {"name": "Alice", "age": 25, "city": "Wonderland"}

In this dictionary, "name", "age", and "city" are keys, and "Alice", 25, and "Wonderland" are their respective values.

Now, let's get our hands dirty with some exercises!

Dictionary Exercise 1: Creating and Accessing Dictionaries

Task: Create a dictionary about your favorite book and access its information.

# Step 1: Create the dictionary
favorite_book = {
    "title": "The Hitchhiker's Guide to the Galaxy",
    "author": "Douglas Adams",
    "year": 1979,
    "genre": "Science Fiction"
}

# Step 2: Access and print information
print(f"My favorite book is {favorite_book['title']} by {favorite_book['author']}.")
print(f"It was published in {favorite_book['year']} and is a {favorite_book['genre']} novel.")

Let's break this down:

  1. We create a dictionary called favorite_book with four key-value pairs.
  2. We use square bracket notation [] to access the values by their keys.
  3. We use f-strings to neatly format our output.

When you run this code, you'll see a nicely formatted description of the book. Cool, right?

Challenge: Add a new key-value pair to the dictionary

Try adding a "rating" to your favorite_book dictionary. Here's how:

favorite_book["rating"] = 5
print(f"I give {favorite_book['title']} a rating of {favorite_book['rating']} out of 5 stars!")

Dictionary Exercise 2: Modifying Dictionaries

Task: Create a dictionary of your weekly schedule and modify it.

# Step 1: Create the schedule dictionary
weekly_schedule = {
    "Monday": "Python class",
    "Tuesday": "Gym",
    "Wednesday": "Movie night",
    "Thursday": "Study group",
    "Friday": "Game night"
}

# Step 2: Print the original schedule
print("Original schedule:")
for day, activity in weekly_schedule.items():
    print(f"{day}: {activity}")

# Step 3: Modify the schedule
weekly_schedule["Tuesday"] = "Yoga class"
weekly_schedule["Saturday"] = "Hiking"

# Step 4: Print the updated schedule
print("\nUpdated schedule:")
for day, activity in weekly_schedule.items():
    print(f"{day}: {activity}")

In this exercise:

  1. We create a dictionary of our weekly schedule.
  2. We use a for loop with the .items() method to iterate through the dictionary and print each day and activity.
  3. We modify an existing entry ("Tuesday") and add a new one ("Saturday").
  4. We print the updated schedule to see our changes.

This exercise shows how flexible dictionaries are. You can easily update existing information or add new data as needed.

Dictionary Exercise 3: Dictionary Methods

Task: Explore useful dictionary methods using a shopping list.

# Step 1: Create a shopping list dictionary
shopping_list = {
    "apples": 5,
    "bananas": 3,
    "milk": 2,
    "bread": 1
}

# Step 2: Use the get() method
print(f"I need to buy {shopping_list.get('apples', 0)} apples.")
print(f"I need to buy {shopping_list.get('oranges', 0)} oranges.")

# Step 3: Use the keys() method
print("\nItems on my shopping list:")
for item in shopping_list.keys():
    print(item)

# Step 4: Use the values() method
total_items = sum(shopping_list.values())
print(f"\nTotal number of items to buy: {total_items}")

# Step 5: Use the pop() method
removed_item = shopping_list.pop('bread', 'Not found')
print(f"\nRemoved {removed_item} from the list.")

# Step 6: Print the final list
print("\nFinal shopping list:")
for item, quantity in shopping_list.items():
    print(f"{item}: {quantity}")

This exercise introduces you to some handy dictionary methods:

  • get(): Safely retrieves a value, returning a default if the key doesn't exist.
  • keys(): Returns a view of all keys in the dictionary.
  • values(): Returns a view of all values in the dictionary.
  • pop(): Removes a key-value pair and returns the value.
  • items(): Returns a view of all key-value pairs as tuples.

These methods make working with dictionaries a breeze!

Dictionary Exercise Programs

Now that we've covered the basics, let's look at some practical programs using dictionaries.

Program 1: Simple Contact Book

def contact_book():
    contacts = {}
    while True:
        action = input("What would you like to do? (add/view/quit): ").lower()
        if action == "quit":
            break
        elif action == "add":
            name = input("Enter the contact's name: ")
            number = input("Enter the contact's number: ")
            contacts[name] = number
            print(f"Added {name} to contacts.")
        elif action == "view":
            if contacts:
                for name, number in contacts.items():
                    print(f"{name}: {number}")
            else:
                print("Your contact book is empty.")
        else:
            print("Invalid action. Please try again.")

contact_book()

This program creates a simple contact book where you can add and view contacts. It demonstrates how dictionaries can be used to store and retrieve information in a user-friendly way.

Program 2: Word Frequency Counter

def word_frequency(sentence):
    words = sentence.lower().split()
    frequency = {}
    for word in words:
        frequency[word] = frequency.get(word, 0) + 1
    return frequency

# Example usage
sample_text = "The quick brown fox jumps over the lazy dog. The dog barks."
result = word_frequency(sample_text)
print("Word frequencies:")
for word, count in result.items():
    print(f"{word}: {count}")

This program counts the frequency of words in a given sentence. It showcases how dictionaries can be used for data analysis and counting occurrences.

Conclusion

Congratulations! You've just completed a whirlwind tour of Python dictionaries. From creating and accessing dictionaries to modifying them and using their built-in methods, you've covered a lot of ground. Remember, practice makes perfect, so don't hesitate to experiment with these concepts in your own projects.

Dictionaries are incredibly powerful tools in Python, and mastering them will open up a world of possibilities in your programming journey. Keep coding, stay curious, and most importantly, have fun! Who knows? You might just find yourself using dictionaries to organize your own hitchhiker's guide to the Python galaxy! ??

Method Description Example
get() Retrieves a value for a given key, with a default if the key is not found dict.get('key', default_value)
keys() Returns a view of all keys in the dictionary dict.keys()
values() Returns a view of all values in the dictionary dict.values()
items() Returns a view of all key-value pairs as tuples dict.items()
pop() Removes a key-value pair and returns the value dict.pop('key', default_value)
update() Updates the dictionary with elements from another dictionary or iterable of key-value pairs dict.update({'new_key': 'new_value'})
clear() Removes all items from the dictionary dict.clear()
copy() Returns a shallow copy of the dictionary new_dict = dict.copy()
setdefault() Returns the value of a key if it exists, otherwise inserts the key with a specified value dict.setdefault('key', default_value)
fromkeys() Creates a new dictionary with specified keys and values dict.fromkeys(['key1', 'key2'], value)

Credits: Image by storyset