A dictionary in Python is a collection of key-value pairs. It is unordered, mutable, and indexed, making it an incredibly versatile data structure for storing and managing related data.
Key Features of Dictionaries
- Key-Value Pairs: Each element in a dictionary is a pair consisting of a unique key and its associated value.
- Keys are Unique: Duplicate keys are not allowed. If you assign a value to an existing key, the old value is overwritten.
- Mutable: You can modify, add, or remove key-value pairs.
- Unordered (Pre-Python 3.7): In Python 3.7+, dictionaries maintain the insertion order.
- Keys are Immutable: Keys must be of an immutable type (e.g., strings, numbers, or tuples).
Creating a Dictionary
You can create a dictionary using curly braces {}
or the dict()
constructor.
# Using curly braces
student = {"name": "John", "age": 25, "grade": "A"}
# Using the dict() constructor
person = dict(name="Alice", age=30, profession="Engineer")
# Empty dictionary
empty_dict = {}
Accessing Dictionary Values
You can access values in a dictionary using their corresponding keys.
student = {"name": "John", "age": 25, "grade": "A"}
# Access value using a key
print(student["name"]) # Output: John
# Using the get() method (avoids KeyError if key doesn't exist)
print(student.get("age")) # Output: 25
print(student.get("school", "Not Found")) # Output: Not Found
Modifying a Dictionary
Adding/Updating Elements
student = {"name": "John", "age": 25}
# Add a new key-value pair
student["grade"] = "A"
# Update an existing key's value
student["age"] = 26
print(student) # Output: {'name': 'John', 'age': 26, 'grade': 'A'}
Removing Elements
student = {"name": "John", "age": 25, "grade": "A"}
# Remove an item using pop()
age = student.pop("age")
print(age) # Output: 25
print(student) # Output: {'name': 'John', 'grade': 'A'}
# Remove an item using del
del student["grade"]
print(student) # Output: {'name': 'John'}
# Remove all items using clear()
student.clear()
print(student) # Output: {}
Dictionary Methods
Method | Description | Example |
---|---|---|
get(key) | Returns the value for the specified key. | d.get('key', 'default') |
keys() | Returns a view object of all the keys in the dictionary. | d.keys() |
values() | Returns a view object of all the values in the dictionary. | d.values() |
items() | Returns a view object of all key-value pairs as tuples. | d.items() |
update() | Updates the dictionary with elements from another dictionary or iterable. | d.update({'key': 'value'}) |
pop(key) | Removes the specified key and returns its value. | d.pop('key') |
popitem() | Removes and returns the last inserted key-value pair. (Python 3.7+) | d.popitem() |
setdefault() | Returns the value of a key. If the key doesn’t exist, inserts it with a value. | d.setdefault('key', 'default') |
clear() | Removes all elements from the dictionary. | d.clear() |
copy() | Returns a shallow copy of the dictionary. | new_dict = d.copy() |
Iterating Through a Dictionary
You can iterate through a dictionary’s keys, values, or items (key-value pairs).
student = {"name": "John", "age": 25, "grade": "A"}
# Iterate through keys
for key in student:
print(key) # Output: name, age, grade
# Iterate through values
for value in student.values():
print(value) # Output: John, 25, A
# Iterate through key-value pairs
for key, value in student.items():
print(f"{key}: {value}")
# Output:
# name: John
# age: 25
# grade: A
Nested Dictionaries
Dictionaries can contain other dictionaries, which is useful for representing structured data.
students = {
"student1": {"name": "John", "age": 25},
"student2": {"name": "Alice", "age": 22},
}
# Access nested dictionary
print(students["student1"]["name"]) # Output: John
# Add a new nested dictionary
students["student3"] = {"name": "Bob", "age": 23}
print(students)
Dictionary Comprehension
Python provides a concise way to create dictionaries using dictionary comprehension.
# Create a dictionary with squares of numbers
squares = {x: x**2 for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Common Use Cases of Dictionaries
- Storing Configurations:
config = {"theme": "dark", "font": "Arial", "font_size": 12}
- Counting Occurrences:
text = "hello world" char_count = {} for char in text: char_count[char] = char_count.get(char, 0) + 1 print(char_count) # Output: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
- Database Representation:
employee = {"id": 101, "name": "John", "position": "Manager"}
Comparison with Lists
Feature | Dictionary | List |
---|---|---|
Structure | Key-Value Pairs | Ordered Collection of Elements |
Access | By Key | By Index |
Duplicates | Keys must be unique | Duplicates are allowed |
Order | Maintains insertion order (3.7+) | Maintains insertion order |
Conclusion
Dictionaries are a fundamental part of Python, offering powerful tools to manage data with key-value pairs. They are especially useful for structured data, quick lookups, and complex data representations.