Access Dictionary Items
What You'll Learn: In this tutorial, you'll discover how to access and work with items in a dictionary using keys. This helps you retrieve and manage data efficiently.
Accessing Items by Key
You can access dictionary items by referring to their key name inside square brackets [].
Example Code:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
Output: Mustang
Using the get() Method
There is also a method called get() that gives the same result.
Example Code:
x = thisdict.get("model")
print(x)
Output: Mustang
Getting Keys
The keys() method returns a list of all the keys in the dictionary.
Example Code:
x = thisdict.keys()
print(x)
Output: dict_keys(['brand', 'model', 'year'])
Adding a new item to the dictionary will update the keys list.
Example Code:
thisdict["color"] = "white"
print(thisdict.keys())
Output: dict_keys(['brand', 'model', 'year', 'color'])
Getting Values
The values() method returns a list of all the values in the dictionary.
Example Code:
x = thisdict.values()
print(x)
Output: dict_values(['Ford', 'Mustang', 1964])
Making changes to the dictionary updates the values list.
Example Code:
thisdict["year"] = 2020
print(thisdict.values())
Output: dict_values(['Ford', 'Mustang', 2020])
Getting Items
The items() method returns each item in the dictionary as tuples in a list.
Example Code:
x = thisdict.items()
print(x)
Output: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
Adding a new item to the dictionary updates the items list.
Example Code:
thisdict["color"] = "red"
print(thisdict.items())
Output: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964), ('color', 'red')])
Checking if a Key Exists
To determine if a specified key is present in a dictionary, use the in keyword.
Example Code:
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Output: Yes, 'model' is one of the keys in the thisdict dictionary
Try It Yourself: Fun Exercises
- Access Your Favorite Books:
- Create a dictionary of your favorite books and their authors.
- Access the author of a specific book using the key.
- List Your Favorite Movies:
- Write a dictionary of movies and their release years.
- Get a list of all the movies using the
keys()method.
- Check Your Snack Inventory:
- Create a dictionary of snacks and their quantities.
- Check if a specific snack is in the dictionary using the
inkeyword.
Summary:
In this Python tutorial, we learned how to access dictionary items using keys, the get() method, and how to retrieve keys, values, and items. We also explored how to check if a key exists in the dictionary. Keep experimenting and have fun with dictionaries in Python!