Creating Dictionaries
Hey there, young Python enthusiast! 🐍 Today, we’re going to dive into the exciting world of dictionaries in Python. Imagine you have a magic book where you can look up anything you want just by saying its name. Well, dictionaries in Python work just like that! They help us store and retrieve information using something called “keys”. Let’s learn how to create our own magic dictionaries step by step!
1. What’s a Dictionary? A dictionary is like a special book with two columns: one for the things you want to look up (we call them “keys”) and another for what those things mean (we call them “values”). Together, they form pairs. For example, if the key is “apple”, the value might be “a delicious fruit.”
2. Creating a Dictionary In Python, making a dictionary is easy-peasy! You use curly braces {}
and separate each key-value pair with a colon :
. Let’s create a simple dictionary:
# Creating a dictionary
my_dict = {"apple": "a delicious fruit", "banana": "a yellow fruit", "orange": "a citrus fruit"}
3. Accessing Values Now that we have our dictionary, we can look up meanings just like finding words in a book! We use the key to get the value. Check this out:
# Accessing values
print(my_dict["apple"]) # Output: a delicious fruit
print(my_dict["banana"]) # Output: a yellow fruit
4. Adding and Modifying Entries Want to add a new word or update an existing one? No problemo! Just assign a value to a new key or an existing key, and you’re good to go:
# Adding new entries
my_dict["grape"] = "a small, juicy fruit"
my_dict["banana"] = "a curved, yellow fruit"
5. Practice Questions: Now, let’s try some exercises to test your dictionary skills:
- Create a dictionary called
ages
with keys as names and values as ages. Add three entries: “Alice” is 10 years old, “Bob” is 12 years old, and “Charlie” is 11 years old. - Access and print the age of “Bob” from the
ages
dictionary. - Add a new entry to the
ages
dictionary: “David” is 9 years old. - Modify the age of “Charlie” to 13 years old.
6. Solutions: Here are the solutions to the practice questions:
# Question 1: Create the dictionary
ages = {"Alice": 10, "Bob": 12, "Charlie": 11}
# Question 2: Access and print Bob's age
print(ages["Bob"]) # Output: 12
# Question 3: Add David's age
ages["David"] = 9
# Question 4: Modify Charlie's age
ages["Charlie"] = 13
Great job, young coder! You’re now a wizard with Python dictionaries! Keep practicing, and soon you’ll be creating dictionaries like a pro. Happy coding! 🚀