Dictionary: Basic syntax and operations
Welcome to the exciting world of Python dictionaries! In this course, we’ll embark on a journey to understand the basics of Python syntax and operations with dictionaries, a powerful tool for organizing and managing data. Don’t worry if you’re new to programming; we’ll break down the concepts into bite-sized pieces, making it as simple as building blocks.
1: What are Dictionaries?
Imagine you have a magical bookshelf where each book has a special tag. This tag helps you quickly find the book you’re looking for. Well, Python dictionaries work in a similar way! Dictionaries are containers that hold pairs of things: a “key” (the tag) and a “value” (the book). Let’s dive into the Python magic:
# Creating a simple dictionary
my_dict = {"apple": 3, "banana": 5, "cherry": 2}
# Accessing values using keys
print(my_dict["banana"]) # Output: 5
2: Basic Operations
Now that we have our magical bookshelf, let’s learn how to add, change, and remove books (key-value pairs) using Python:
# Adding a new item
my_dict["orange"] = 4
# Updating the value of an existing item
my_dict["banana"] = 7
# Removing an item
del my_dict["cherry"]
3: Common Operations
Let’s explore some common operations, like checking if a key is in the dictionary and getting the number of items:
# Checking if a key exists
print("apple" in my_dict) # Output: True
# Getting the number of items (key-value pairs)
print(len(my_dict)) # Output: 3
Practice Questions:
- Create a dictionary representing your favorite fruits and their quantities.
- Add a new fruit to your dictionary.
- Update the quantity of one of your favorite fruits.
- Check if “watermelon” is in your dictionary.
- Remove a fruit from your dictionary.
Solutions:
favorite_fruits = {"apple": 2, "banana": 3, "orange": 1}
favorite_fruits["grape"] = 4
favorite_fruits["banana"] = 5
print("watermelon" in favorite_fruits)
# Output: False
del favorite_fruits["orange"]
Congratulations! You’ve just unlocked the basics of Python dictionaries. Keep practicing, and soon you’ll be a master of organizing data with these magical key-value pairs!