Python Dictionaries: A Comprehensive Guide
Dictionaries are one of the most powerful and versatile data structures in Python. They allow you to store data in key-value pairs, making it easy to retrieve information based on a unique identifier (the key). This guide will cover the fundamentals of dictionaries, including creation, access, modification, and common operations.
1. What is a Dictionary?
- Key-Value Pairs: Dictionaries store data as pairs of keys and their corresponding values.
- Unordered: Dictionaries are unordered (until Python 3.7, where insertion order is preserved as an implementation detail, and guaranteed in Python 3.8+). This means the items in a dictionary don't have a specific order.
- Mutable: Dictionaries are mutable, meaning you can change their contents after they're created.
- Unique Keys: Keys must be unique within a dictionary. If you try to use the same key multiple times, the last value associated with that key will be stored.
- Key Types: Keys must be immutable data types, such as strings, numbers, or tuples. Lists cannot be used as keys because they are mutable.
- Value Types: Values can be of any data type, including other dictionaries, lists, or even functions.
2. Creating Dictionaries
There are several ways to create dictionaries in Python:
a) Using Curly Braces {}:
# Empty dictionary
my_dict = {}
# Dictionary with initial key-value pairs
student = {
"name": "Alice",
"age": 20,
"major": "Computer Science"
}
print(student) # Output: {'name': 'Alice', 'age': 20, 'major': 'Computer Science'}
b) Using the dict() Constructor:
# From keyword arguments
student = dict(name="Bob", age=22, major="Engineering")
print(student) # Output: {'name': 'Bob', 'age': 22, 'major': 'Engineering'}
# From a list of tuples
pairs = [("city", "New York"), ("country", "USA")]
city_dict = dict(pairs)
print(city_dict) # Output: {'city': 'New York', 'country': 'USA'}
3. Accessing Dictionary Values
You access values in a dictionary using their corresponding keys within square brackets [].
student = {"name": "Alice", "age": 20, "major": "Computer Science"}
print(student["name"]) # Output: Alice
print(student["age"]) # Output: 20
# Using the get() method (safer)
print(student.get("major")) # Output: Computer Science
print(student.get("grade")) # Output: None (doesn't raise an error)
print(student.get("grade", "N/A")) # Output: N/A (default value if key not found)
Important: Trying to access a key that doesn't exist using [] will raise a KeyError. The get() method is a safer way to access values because it returns None (or a specified default value) if the key is not found, preventing the error.
4. Modifying Dictionaries
Dictionaries are mutable, so you can add, update, and delete key-value pairs.
a) Adding Key-Value Pairs:
student = {"name": "Alice", "age": 20}
student["grade"] = "A" # Adds a new key-value pair
print(student) # Output: {'name': 'Alice', 'age': 20, 'grade': 'A'}
b) Updating Values:
student = {"name": "Alice", "age": 20}
student["age"] = 21 # Updates the value associated with the "age" key
print(student) # Output: {'name': 'Alice', 'age': 21}
c) Deleting Key-Value Pairs:
delkeyword:student = {"name": "Alice", "age": 20, "major": "Computer Science"} del student["major"] print(student) # Output: {'name': 'Alice', 'age': 20}pop()method: Removes a key and returns its value.student = {"name": "Alice", "age": 20, "major": "Computer Science"} major = student.pop("major") print(student) # Output: {'name': 'Alice', 'age': 20} print(major) # Output: Computer Sciencepopitem()method: Removes and returns an arbitrary (key, value) pair as a tuple. (In Python 3.7+, it removes the last inserted item).student = {"name": "Alice", "age": 20, "major": "Computer Science"} item = student.popitem() print(student) # Output: (order may vary) {'name': 'Alice', 'age': 20} print(item) # Output: ('major', 'Computer Science')clear()method: Removes all items from the dictionary.student = {"name": "Alice", "age": 20} student.clear() print(student) # Output: {}
5. Common Dictionary Operations
len(dictionary): Returns the number of key-value pairs in the dictionary.key in dictionary: Checks if a key exists in the dictionary (returnsTrueorFalse).dictionary.keys(): Returns a view object containing all the keys in the dictionary.dictionary.values(): Returns a view object containing all the values in the dictionary.dictionary.items(): Returns a view object containing all the key-value pairs as tuples.dictionary.copy(): Creates a shallow copy of the dictionary.dictionary.update(other_dictionary): Merges the key-value pairs fromother_dictionaryinto the original dictionary. If a key exists in both dictionaries, the value fromother_dictionaryoverwrites the value in the original dictionary.
student = {"name": "Alice", "age": 20, "major": "Computer Science"}
print(len(student)) # Output: 3
print("name" in student) # Output: True
print("grade" in student) # Output: False
keys = student.keys()
print(keys) # Output: dict_keys(['name', 'age', 'major'])
values = student.values()
print(values) # Output: dict_values(['Alice', 20, 'Computer Science'])
items = student.items()
print(items) # Output: dict_items([('name', 'Alice'), ('age', 20), ('major', 'Computer Science')])
student_copy = student.copy()
print(student_copy) # Output: {'name': 'Alice', 'age': 20, 'major': 'Computer Science'}
another_student = {"gpa": 3.8, "name": "Charlie"}
student.update(another_student)
print(student) # Output: {'name': 'Charlie', 'age': 20, 'major': 'Computer Science', 'gpa': 3.8}
6. Dictionary Comprehension
Dictionary comprehension provides a concise way to create dictionaries.
# Create a dictionary mapping numbers to their squares
squares = {x: x**2 for x in range(5)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Create a dictionary from a list of names, mapping each name to its length
names = ["Alice", "Bob", "Charlie"]
name_lengths = {name: len(name) for name in names}
print(name_lengths) # Output: {'Alice': 5, 'Bob': 3, 'Charlie': 7}
7. Nested Dictionaries
Dictionaries can contain other dictionaries as values, creating nested structures.
student = {
"name": "Alice",
"age": 20,
"address": {
"street": "123 Main St",
"city": "Anytown",
"zip": "12345"
}
}
print(student["address"]["city"]) # Output: Anytown
Conclusion
Dictionaries are a fundamental data structure in Python, offering a flexible and efficient way to store and retrieve data. Understanding