Python – Access Dictionary Items

Welcome to The Coding College! In this tutorial, we’ll explore how to access dictionary items in Python. Whether you’re new to Python or brushing up on your skills, understanding how to retrieve values from dictionaries is essential for working with structured data.

What Are Dictionary Items?

In Python, a dictionary is a collection of key-value pairs. Each key acts as a label for its associated value, and you can access a value by referring to its key.

Example of a Dictionary:

person = {  
    "name": "Alice",  
    "age": 25,  
    "city": "New York"  
}  

Here, name, age, and city are keys, and their respective values are "Alice", 25, and "New York".

Accessing Dictionary Items

You can access a dictionary item by its key using two common methods:

  1. Using Square Brackets
  2. Using the get() Method

Method 1: Using Square Brackets

Square brackets are the most direct way to access dictionary items.

Example:

person = {"name": "Alice", "age": 25, "city": "New York"}  

# Access the value of the 'name' key  
print(person["name"])  # Output: Alice  

# Access the value of the 'age' key  
print(person["age"])  # Output: 25  

Important Note:

If the key does not exist, Python will raise a KeyError.

Method 2: Using the get() Method

The get() method is a safer way to access dictionary items because it returns None (or a default value) if the key does not exist.

Example:

person = {"name": "Alice", "age": 25}  

# Access the value of the 'city' key using get()  
print(person.get("city"))  # Output: None  

# Provide a default value  
print(person.get("city", "Not Found"))  # Output: Not Found  

Accessing All Keys, Values, or Items

You can retrieve all keys, values, or both key-value pairs using the following methods:

Access All Keys

person = {"name": "Alice", "age": 25, "city": "New York"}  
print(person.keys())  

Output:

dict_keys(['name', 'age', 'city'])  

Access All Values

print(person.values())  

Output:

dict_values(['Alice', 25, 'New York'])  

Access All Key-Value Pairs

print(person.items())  

Output:

dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])  

Looping Through Dictionary Items

You can loop through a dictionary to access keys, values, or both.

Example:

person = {"name": "Alice", "age": 25, "city": "New York"}  

# Loop through keys  
for key in person:  
    print(key)  

# Loop through values  
for value in person.values():  
    print(value)  

# Loop through key-value pairs  
for key, value in person.items():  
    print(f"{key}: {value}")  

Output:

name  
age  
city  
Alice  
25  
New York  
name: Alice  
age: 25  
city: New York  

Checking for a Key in a Dictionary

To check if a key exists in a dictionary, use the in keyword.

Example:

person = {"name": "Alice", "age": 25}  

# Check if 'name' exists  
print("name" in person)  # Output: True  

# Check if 'city' exists  
print("city" in person)  # Output: False  

Practice Exercises

Exercise 1: Access a Dictionary Item

Given the dictionary:

fruit_prices = {"apple": 2, "banana": 1, "cherry": 3}  
  • Access the price of banana using square brackets.

Exercise 2: Safely Access a Missing Key

Using the dictionary from Exercise 1, try to access the price of mango using the get() method with a default value of "Price not available".

Exercise 3: Loop Through a Dictionary

Using the dictionary:

student_scores = {"John": 85, "Jane": 92, "Dave": 78}  
  • Print each student’s name and their score.

Why Learn with The Coding College?

At The Coding College, we focus on practical, user-friendly tutorials that help you master programming concepts step-by-step. Understanding how to access dictionary items is fundamental to writing efficient and effective Python code.

Conclusion

Accessing dictionary items is a fundamental skill that you’ll use frequently in Python programming. Whether retrieving a single value, looping through a dictionary, or safely handling missing keys, Python provides flexible and efficient ways to work with dictionaries.

Leave a Comment