Python Dictionaries
A dictionary in Python is an unordered, mutable collection of items that stores data in key-value pairs. Each key in a dictionary is unique, and it is associated with a corresponding value. Dictionaries are highly versatile and allow for fast lookups, insertions, and deletions of values based on their keys.
Table of Contents
Key Characteristics of Dictionaries:
- Unordered: Prior to Python 3.7, dictionaries did not maintain the insertion order of items. From Python 3.7 onwards, dictionaries maintain the order of insertion.
- Mutable: You can change, add, or remove items from a dictionary after it is created.
- Key-Value Pairs: Each entry in a dictionary is a key-value pair.
- Keys are Unique: Dictionary keys must be unique, while values can be duplicated.
- Keys are Immutable: Keys must be of an immutable type, such as strings, numbers, or tuples.
Creating Dictionaries
You can create a dictionary by using curly braces {}
and specifying key-value pairs, separated by commas. Each key is followed by its corresponding value, with a colon :
separating the two.
Example:
# Creating a dictionary
student = {
"name": "Alice",
"age": 25,
"major": "Computer Science"
}
print(student) # Output: {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
Empty Dictionary
You can create an empty dictionary by using empty curly braces {}
or the dict()
function.
# Empty dictionary
empty_dict = {}
empty_dict_via_function = dict()
print(empty_dict) # Output: {}
Accessing Dictionary Values
You can access the value associated with a particular key by using square brackets []
or the get()
method. If you attempt to access a key that does not exist, Python will raise a KeyError
.
Accessing Using Square Brackets:
student = {"name": "Alice", "age": 25, "major": "Computer Science"}
# Access value using the key
print(student["name"]) # Output: Alice
# Accessing a non-existent key raises KeyError
# print(student["gender"]) # KeyError: 'gender'
Accessing Using get()
Method:
The get()
method is a safer way to access a value because it returns None
if the key does not exist, or you can provide a default value.
# Using get() method
print(student.get("name")) # Output: Alice
print(student.get("gender")) # Output: None
print(student.get("gender", "Not specified")) # Output: Not specified
Adding and Modifying Dictionary Items
You can add new key-value pairs to a dictionary or modify the value of an existing key by using square brackets.
Adding a New Key-Value Pair:
student = {"name": "Alice", "age": 25}
student["major"] = "Computer Science" # Adding a new key-value pair
print(student) # Output: {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
Modifying an Existing Key:
student["age"] = 26 # Modifying an existing key-value pair
print(student) # Output: {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
Removing Items from a Dictionary
You can remove items from a dictionary using several methods:
pop()
: Removes the item with the specified key and returns its value.del
: Deletes the key-value pair using the key.popitem()
: Removes the last inserted key-value pair.clear()
: Removes all items from the dictionary.
Using pop()
Method:
# pop() removes the item with the specified key and returns its value
age = student.pop("age")
print(age) # Output: 26
print(student) # Output: {'name': 'Alice', 'major': 'Computer Science'}
Using del
Keyword:
# del keyword removes the key-value pair
del student["major"]
print(student) # Output: {'name': 'Alice'}
Using popitem()
Method:
# popitem() removes the last inserted key-value pair
student = {"name": "Alice", "age": 25, "major": "Computer Science"}
last_item = student.popitem()
print(last_item) # Output: ('major', 'Computer Science')
print(student) # Output: {'name': 'Alice', 'age': 25}
Using clear()
Method:
# clear() removes all key-value pairs from the dictionary
student.clear()
print(student) # Output: {}
Checking for Existence of a Key
You can check if a key exists in a dictionary using the in
keyword.
Example:
student = {"name": "Alice", "age": 25}
# Check if the key "age" exists in the dictionary
print("age" in student) # Output: True
# Check if the key "gender" exists in the dictionary
print("gender" in student) # Output: False
Iterating Over a Dictionary
You can iterate over the keys, values, or key-value pairs of a dictionary using loops.
Iterating Over Keys:
student = {"name": "Alice", "age": 25, "major": "Computer Science"}
# Looping through keys
for key in student:
print(key)
# Output:
# name
# age
# major
Iterating Over Values:
# Looping through values
for value in student.values():
print(value)
# Output:
# Alice
# 25
# Computer Science
Iterating Over Key-Value Pairs:
# Looping through key-value pairs
for key, value in student.items():
print(f"{key}: {value}")
# Output:
# name: Alice
# age: 25
# major: Computer Science
Dictionary Methods
Dictionaries come with a variety of built-in methods. Here are some commonly used ones:
keys()
: Returns a view object containing all the keys in the dictionary.values()
: Returns a view object containing all the values in the dictionary.items()
: Returns a view object containing all key-value pairs as tuples.update()
: Updates the dictionary with key-value pairs from another dictionary or iterable.copy()
: Returns a shallow copy of the dictionary.
Example of Using update()
:
student = {"name": "Alice", "age": 25}
extra_info = {"major": "Computer Science", "graduation_year": 2024}
student.update(extra_info) # Merging dictionaries
print(student)
# Output: {'name': 'Alice', 'age': 25, 'major': 'Computer Science', 'graduation_year': 2024}
Example of Using copy()
:
# Making a shallow copy of a dictionary
student_copy = student.copy()
print(student_copy) # Output: {'name': 'Alice', 'age': 25, 'major': 'Computer Science', 'graduation_year': 2024}
Dictionary Comprehension
Similar to list comprehension, you can create dictionaries using dictionary comprehension.
Example:
# Dictionary comprehension: Create a dictionary of squares of numbers from 1 to 5
squares = {x: x**2 for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
When to Use Dictionaries
- Fast Lookups: Dictionaries provide fast lookups based on unique keys.
- When You Need to Map Data: Use dictionaries when you want to map a set of unique keys to corresponding values.
- Flexible Data Storage: Dictionaries can store heterogeneous data, including other dictionaries, lists, or objects, making them useful for complex data structures.
Key Concepts Recap
- Dictionaries store data in key-value pairs.
- Keys must be unique and immutable (e.g., strings, numbers, tuples).
- Values can be of any data type and can be duplicated.
- You can add, modify, and remove items from a dictionary.
- Use dictionary methods like
get()
,update()
,pop()
, andclear()
for working with dictionary items. - Dictionary comprehension allows you to create dictionaries concisely.
- Iterating through dictionaries can be done over keys, values, or key-value pairs.
Exercise:
- Create a dictionary representing a book with keys such as
title
,author
,year
, andgenre
. Then:- Add a key for
ISBN
and its corresponding value. - Remove the
genre
key from the dictionary. - Update the
year
of publication.
- Add a key for
- Write a function that takes a dictionary representing a student’s grades in different subjects and returns the average grade.
- Create a dictionary comprehension to generate a dictionary where the keys are numbers from 1 to 5 and the values are their cubes.
Next time, we’ll look at how to improve your Python code structure with Python functions!
FAQ
Q1: Can dictionary keys be of any data type?
A1: No, dictionary keys must be immutable data types. Common examples of valid keys include:
- Strings
- Numbers (integers or floats)
- Tuples (if they contain only immutable elements)
Data types like lists or dictionaries cannot be used as keys because they are mutable.
Q2: Can a dictionary have duplicate keys?
A2: No, dictionary keys must be unique. If you try to assign a value to a key that already exists, it will overwrite the existing value. However, dictionary values can be duplicated.
Example:
student = {"name": "Alice", "age": 25, "name": "Bob"}
print(student) # Output: {'name': 'Bob', 'age': 25}
In this case, the key "name"
appears twice, but only the second assignment is retained.
Q3: How do I check if a key exists in a dictionary?
A3: You can check if a key exists in a dictionary using the in
keyword.
Example:
student = {"name": "Alice", "age": 25}
# Check if the key "age" exists
print("age" in student) # Output: True
# Check if the key "gender" exists
print("gender" in student) # Output: False
Alternatively, you can use the get()
method to safely retrieve a value and return None
or a default value if the key doesn’t exist.
Q4: What happens if I try to access a non-existent key using square brackets ([]
)?
A4: If you try to access a key that does not exist in the dictionary using square brackets, Python raises a KeyError
.
Example:
student = {"name": "Alice"}
# Accessing a non-existent key raises KeyError
# print(student["age"]) # KeyError: 'age'
To avoid this, you can use the get()
method, which returns None
or a specified default value if the key does not exist.
Q5: What is the difference between pop()
and del
when removing dictionary items?
A5:
pop()
removes a key-value pair by key and returns the value.del
removes a key-value pair by key but does not return the value.
Example of pop()
:
student = {"name": "Alice", "age": 25}
age = student.pop("age")
print(age) # Output: 25
print(student) # Output: {'name': 'Alice'}
Example of del
:
student = {"name": "Alice", "age": 25}
del student["age"]
print(student) # Output: {'name': 'Alice'}
Q6: How do I merge two dictionaries?
A6: You can merge two dictionaries using the update()
method, which updates the first dictionary with key-value pairs from the second. If the same key exists in both dictionaries, the value from the second dictionary will overwrite the value in the first.
Example:
student = {"name": "Alice", "age": 25}
extra_info = {"major": "Computer Science", "age": 26}
student.update(extra_info)
print(student)
# Output: {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
Alternatively, from Python 3.9 onwards, you can use the |
operator to merge dictionaries:
merged_dict = student | extra_info
Q7: How do I loop through both keys and values in a dictionary?
A7: You can use the items()
method to loop through both keys and values at the same time:
Example:
student = {"name": "Alice", "age": 25}
for key, value in student.items():
print(f"{key}: {value}")
# Output:
# name: Alice
# age: 25
Q8: How can I get all the keys or all the values from a dictionary?
A8: To get all the keys, use the keys()
method:
student = {"name": "Alice", "age": 25}
print(student.keys()) # Output: dict_keys(['name', 'age'])
To get all the values, use the values()
method:
print(student.values()) # Output: dict_values(['Alice', 25])
These methods return view objects that behave like sets.
Q9: How do I create a dictionary using dictionary comprehension?
A9: You can use dictionary comprehension to create a dictionary in a concise way. The syntax is similar to list comprehension, but it involves key-value pairs.
Example:
# Dictionary comprehension: Create a dictionary where keys are numbers and values are their squares
squares = {x: x**2 for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Q10: Can I use a list or another dictionary as a key in a dictionary?
A10: No, you cannot use a list or dictionary as a key because they are mutable types and not hashable. Only immutable types, such as strings, numbers, or tuples (if the tuple contains only immutable elements), can be used as keys in a dictionary.
Q11: How do I make a copy of a dictionary?
A11: You can make a shallow copy of a dictionary using the copy()
method. This creates a new dictionary with the same key-value pairs as the original.
Example:
student = {"name": "Alice", "age": 25}
student_copy = student.copy()
print(student_copy) # Output: {'name': 'Alice', 'age': 25}
You can also use dict()
to create a copy:
student_copy = dict(student)
Q12: How are dictionaries different from lists?
A12:
- Dictionaries store data in key-value pairs, allowing for fast lookup by key. The keys must be unique and immutable.
- Lists store ordered sequences of elements that can be accessed by index. Lists allow duplicate values and can store any data type.
Use dictionaries when you need to map unique keys to values and look up values efficiently by their keys. Use lists when you need to store an ordered collection of items and access them by position (index).
Q13: Can I nest dictionaries inside other dictionaries?
A13: Yes, dictionaries can contain other dictionaries as values. This is useful for representing complex hierarchical data.
Example of a nested dictionary:
student = {
"name": "Alice",
"courses": {
"math": 90,
"science": 85
}
}
# Accessing a nested value
print(student["courses"]["math"]) # Output: 90