- Key indexing — accessing values using keys
- get() method — safely retrieving values
- Adding items — adding new key-value pairs
- Updating items — modifying existing values
- Deleting items — removing key-value pairs
- Common mistakes — and how to avoid them
Introduction to Dictionary Access
Accessing items in a dictionary is a fundamental operation in Python. Unlike lists which use numeric indices, dictionaries use keys to access values. This makes dictionaries ideal for storing and retrieving data by a meaningful identifier.
The primary methods for accessing dictionary items are:
- Key indexing — using
dict[key]to retrieve values - get() method — safely retrieving values with a default
- Adding items — assigning values to new keys
- Updating items — modifying existing key-value pairs
- Deleting items — removing key-value pairs
💡 Key concept: Dictionaries provide fast lookups by key (O(1) average time complexity), making them ideal for data retrieval operations.
Key Indexing
Accessing Values Using Keys
The most direct way to access a dictionary value is to use the key inside square brackets []. This is similar to list indexing but uses keys instead of positions.
# Basic key indexing
person = {"name": "Alice", "age": 25, "city": "NYC"}
print(person["name"]) # Alice
print(person["age"]) # 25
print(person["city"]) # NYC
# Accessing nested dictionary values
user = {
"name": "Alice",
"address": {
"street": "123 Main St",
"city": "NYC",
"zip": "10001"
}
}
print(user["address"]["city"]) # NYC
# Using variables as keys
key = "name"
print(person[key]) # Alice
# Working with different key types
data = {
"string_key": "value1",
42: "value2",
(1, 2): "value3"
}
print(data["string_key"]) # value1
print(data[42]) # value2
print(data[(1, 2)]) # value3
Characteristics:
- Uses
dict[key]syntax - Raises
KeyErrorif the key doesn't exist - Works with any hashable key type
- Time complexity: O(1) on average
Quick Check: What happens when you try to access a non-existent key using dict[key]? (Answer: KeyError is raised)
Using get() Method
Safe Value Retrieval
The get() method provides a safe way to retrieve values from a dictionary. If the key doesn't exist, it returns a default value instead of raising an error.
# Basic get() usage
person = {"name": "Alice", "age": 25}
print(person.get("name")) # Alice
print(person.get("city")) # None (default)
print(person.get("city", "Unknown")) # Unknown
# Working with different default values
config = {"host": "localhost", "port": 8080}
print(config.get("host", "127.0.0.1")) # localhost
print(config.get("timeout", 30)) # 30
# Checking if a key exists
if person.get("city") is None:
print("City not found")
# get() with nested dictionaries
user = {"name": "Alice", "address": {"city": "NYC"}}
city = user.get("address", {}).get("city", "Unknown")
print(city) # NYC
# Practical use: counting with get()
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts) # {'apple': 3, 'banana': 2, 'cherry': 1}
Characteristics:
- Returns the value if the key exists
- Returns
Noneor a default value if the key doesn't exist - No error is raised
- Ideal for safe data retrieval
Quick Check: What does get() return if the key is not found? (Answer: None or the specified default value)
Adding Items
Adding New Key-Value Pairs
Adding items to a dictionary is done by assigning a value to a new key. If the key doesn't exist, it is created.
# Adding a new key-value pair
person = {"name": "Alice", "age": 25}
person["city"] = "NYC"
print(person) # {'name': 'Alice', 'age': 25, 'city': 'NYC'}
# Adding multiple items
person["email"] = "alice@example.com"
person["phone"] = "555-1234"
print(person) # {'name': 'Alice', 'age': 25, 'city': 'NYC', 'email': 'alice@example.com', 'phone': '555-1234'}
# Adding with variable keys
key = "country"
person[key] = "USA"
print(person) # {'name': 'Alice', 'age': 25, 'city': 'NYC', 'email': 'alice@example.com', 'phone': '555-1234', 'country': 'USA'}
# Adding to a nested dictionary
person["address"] = {}
person["address"]["street"] = "123 Main St"
person["address"]["zip"] = "10001"
print(person) # {'name': 'Alice', 'age': 25, 'city': 'NYC', 'email': 'alice@example.com', 'phone': '555-1234', 'country': 'USA', 'address': {'street': '123 Main St', 'zip': '10001'}}
Characteristics:
- New keys are added automatically
- If the key already exists, the value is updated
- Keys can be any hashable type
- Values can be any data type
Quick Check: What happens when you assign a value to an existing key? (Answer: The existing value is updated)
Updating Items
Modifying Existing Values
Updating values in a dictionary is done by assigning a new value to an existing key. The update() method can also be used to update multiple items.
# Updating a single value
person = {"name": "Alice", "age": 25, "city": "NYC"}
person["age"] = 26
print(person) # {'name': 'Alice', 'age': 26, 'city': 'NYC'}
# Using update() method
person.update({"city": "LA", "age": 27})
print(person) # {'name': 'Alice', 'age': 27, 'city': 'LA'}
# Updating multiple values
person.update({"email": "alice@example.com", "phone": "555-1234"})
print(person) # {'name': 'Alice', 'age': 27, 'city': 'LA', 'email': 'alice@example.com', 'phone': '555-1234'}
# Using update() with keyword arguments
person.update(age=28, city="SF")
print(person) # {'name': 'Alice', 'age': 28, 'city': 'SF', 'email': 'alice@example.com', 'phone': '555-1234'}
# Using update() with a list of tuples
person.update([("age", 29), ("city", "NYC")])
print(person) # {'name': 'Alice', 'age': 29, 'city': 'NYC', 'email': 'alice@example.com', 'phone': '555-1234'}
Methods:
- Direct assignment —
dict[key] = new_value - update() — updates with another dictionary or iterable
- Both methods modify the dictionary in place
- If keys don't exist, they are added
Quick Check: What does update() do if the key doesn't exist? (Answer: It adds the new key-value pair)
Deleting Items
Removing Key-Value Pairs
Items can be removed from a dictionary using the del statement, pop() method, or popitem() method.
# Using del statement
person = {"name": "Alice", "age": 25, "city": "NYC", "email": "alice@example.com"}
del person["email"]
print(person) # {'name': 'Alice', 'age': 25, 'city': 'NYC'}
# Using pop() (removes and returns value)
person = {"name": "Alice", "age": 25, "city": "NYC"}
city = person.pop("city")
print(city) # NYC
print(person) # {'name': 'Alice', 'age': 25}
# pop() with default value
age = person.pop("age", 0)
print(age) # 25
country = person.pop("country", "Unknown")
print(country) # Unknown
# Using popitem() (removes and returns last inserted item)
person = {"name": "Alice", "age": 25, "city": "NYC"}
item = person.popitem()
print(item) # ('city', 'NYC')
print(person) # {'name': 'Alice', 'age': 25}
# Using clear() (removes all items)
person.clear()
print(person) # {}
Methods:
- del dict[key] — removes the key-value pair
- pop(key) — removes and returns the value
- popitem() — removes and returns the last inserted item
- clear() — removes all items
Quick Check: What is the difference between pop() and del? (Answer: pop() returns the removed value; del does not)
Common Mistakes
Watch Out For These!
Mistake 1: Accessing Non-Existent Keys
# WRONG — raises KeyError
person = {"name": "Alice", "age": 25}
# city = person["city"] # KeyError: 'city'
# CORRECT — use get()
city = person.get("city", "Unknown")
print(city) # Unknown
Mistake 2: Using Mutable Keys
# WRONG — raises TypeError
my_dict = {}
# my_dict[[1, 2]] = "value" # TypeError: unhashable type: 'list'
# CORRECT — use immutable types
my_dict[(1, 2)] = "value"
Mistake 3: Forgetting that update() Modifies in Place
# WRONG — expecting a new dictionary
person = {"name": "Alice", "age": 25}
new_person = person.update({"city": "NYC"}) # Returns None
print(new_person) # None
# CORRECT — update modifies in place
person.update({"city": "NYC"})
print(person) # {'name': 'Alice', 'age': 25, 'city': 'NYC'}
Quick Check: What is the most common mistake when accessing dictionary items? (Answer: Accessing a non-existent key without checking)
Interactive Editor
Experiment with accessing dictionary items directly in your browser. Modify the code and see the results in real time.
DICTIONARY ACCESS PRACTICE
========================================
Original: {'name': 'Alice', 'age': 25, 'city': 'NYC'}
1. KEY INDEXING
Name: Alice
Age: 25
2. GET() METHOD
get('city'): NYC
get('country', 'USA'): USA
3. ADDING ITEMS
After adding: {'name': 'Alice', 'age': 25, 'city': 'NYC', 'email': 'alice@example.com', 'phone': '555-1234'}
4. UPDATING ITEMS
After updating: {'name': 'Alice', 'age': 26, 'city': 'LA', 'email': 'alice@example.com', 'phone': '555-5678'}
5. DELETING ITEMS
Removed phone: 555-5678
After pop: {'name': 'Alice', 'age': 26, 'city': 'LA', 'email': 'alice@example.com'}
After del: {'name': 'Alice', 'age': 26, 'city': 'LA'}
6. GET() FOR COUNTING
Word counts: {'apple': 3, 'banana': 2, 'cherry': 1}
Dictionary access practice complete!
Certificate of Completion
You have completed the Python Dictionary Access Items tutorial. You understand key indexing, get() method, adding, updating, and deleting dictionary items.
Quick Quiz — Test Your Knowledge
Let's see what you've learned about accessing dictionary items:
Frequently Asked Questions
What is the difference between dict[key] and dict.get(key)?
dict[key] raises a KeyError if the key doesn't exist. dict.get(key) returns None or a default value if the key doesn't exist, without raising an error.
How do I add multiple items to a dictionary at once?
update() method: dict.update({"key1": value1, "key2": value2}) or dict.update([("key1", value1), ("key2", value2)]).
What is the difference between pop() and popitem()?
pop(key) removes and returns the value for a specific key. popitem() removes and returns the last inserted key-value pair (or an arbitrary pair in older Python versions).
Can I use variables as dictionary keys?
key = "name"; value = dict[key]. The variable value is used as the key.
How do I check if a key exists in a dictionary?
in operator: if key in dict: or use dict.get(key) and check for None.
What does dict.update() return?
dict.update() returns None. It modifies the dictionary in place.
Where to Go From Here
After mastering dictionary access, consider exploring these related topics:
Dictionary Methods
Explore all built-in dictionary methods and operations.
Learn More →Iterate Dictionary
Learn different ways to loop through dictionaries.
Learn More →Nested Dictionaries
Work with dictionaries within dictionaries.
Learn More →