Interview Questions, Answers and Tutorials

Python Dictionaries: Accessing Values with Keys

Python Dictionaries: Accessing Values with Keys

Hey there Python pals! Have you ever wanted to unlock secret treasures hidden in Python dictionaries? Well, today is your lucky day! In this fun and exciting course, we’re going to learn all about accessing values using keys in Python dictionaries. But don’t worry, I’ll explain everything in a way that even a 10-year-old can understand!

What is a Dictionary? Imagine you have a magic bookshelf where you can keep all your toys. Each toy has a special label. A dictionary in Python is just like that magic bookshelf! It’s a collection of items, each with its own label, called a “key”. And guess what? Instead of toys, we store all sorts of things like numbers, words, or even other dictionaries!

Accessing Values with Keys: Now, let’s talk about the cool part – accessing the goodies stored in our dictionary using their labels (keys). It’s just like asking your magic bookshelf to give you a specific toy by telling it the label!

Here’s how we do it in Python:

# Let's create a dictionary of toys and their quantities
toys = {'car': 3, 'doll': 5, 'ball': 2}

# Now, let's get the quantity of the 'doll'
doll_quantity = toys['doll']
print("Number of dolls:", doll_quantity)

In this example, we asked Python to give us the quantity of dolls by saying toys['doll']. Python then looked inside the dictionary, found the ‘doll’ label, and gave us the quantity, which we stored in the variable doll_quantity.

Practice Time: Now, it’s time for you to practice! Try these questions:

  1. Given the dictionary fruits = {'apple': 5, 'banana': 3, 'orange': 7}, how would you find the quantity of oranges?
  2. Create a dictionary called ages where keys are people’s names and values are their ages. Access the age of ‘Alice’ from the dictionary.
  3. Think of your favorite things and create a dictionary to store them. Access one of your favorite things using its label.

Solutions:

fruits = {'apple': 5, 'banana': 3, 'orange': 7}
orange_quantity = fruits['orange']
print("Number of oranges:", orange_quantity)

ages = {'Alice': 25, 'Bob': 30, 'Charlie': 35}
alice_age = ages['Alice']
print("Alice's age:", alice_age)

  1. (Example answer)

favorites = {'toy': 'teddy bear', 'food': 'pizza', 'color': 'blue'}
favorite_toy = favorites['toy']
print("My favorite toy:", favorite_toy)

Great job, explorers! You’ve learned how to unlock the treasures hidden in Python dictionaries using keys. Now you can access any value you want just like a pro! Keep practicing, and soon you’ll be a master of Python dictionaries. Happy coding! 🚀🐍