A dictionary is an unordered collection of key-value pairs. Unlike lists and tuples, which store values in sequences, dictionaries store data in a key-value mapping, allowing for fast retrieval and modification.
1. Creating a Dictionary
Dictionaries are defined using curly braces {}
with key-value pairs separated by colons :
.
Example:
student = {
"name": "Alice",
"age": 21,
"grade": "A"
}
print(student)
Output:
{'name': 'Alice', 'age': 21, 'grade': 'A'}
Each key in a dictionary must be unique, and keys can be of any immutable data type (e.g., str
, int
, tuple
).
2. Accessing Dictionary Values
You can access values using their keys.
Example:
print(student["name"]) # Output: Alice
print(student.get("age")) # Output: 21
Using .get()
prevents errors if the key does not exist.
3. Modifying a Dictionary
Dictionaries are mutable, allowing modification of existing values or addition of new key-value pairs.
Example:
student["age"] = 22 # Modify existing key
student["city"] = "New York" # Add new key-value pair
print(student)
4. Removing Elements
Use del
, pop()
, or popitem()
to remove elements.
Example:
del student["grade"] # Delete a specific key
print(student.pop("age")) # Remove and return the value of 'age'
print(student.popitem()) # Remove and return the last inserted key-value pair
5. Dictionary Methods
Python provides several built-in methods to work with dictionaries.
Example:
print(student.keys()) # Get all keys
print(student.values()) # Get all values
print(student.items()) # Get key-value pairs
6. Looping Through a Dictionary
You can iterate over keys, values, or key-value pairs.
Example:
for key, value in student.items():
print(key, "->", value)
7. Nested Dictionaries
Dictionaries can contain other dictionaries.
Example:
students = {
"Alice": {"age": 21, "grade": "A"},
"Bob": {"age": 22, "grade": "B"}
}
print(students["Alice"]["grade"]) # Output: A
8. Dictionary Comprehension
Similar to list comprehensions, you can create dictionaries concisely.
Example:
squares = {x: x**2 for x in range(1, 6)}
print(squares)
9. Converting Between Dictionaries and Other Data Types
Example:
# Convert list of tuples to dictionary
tuple_list = [("name", "Alice"), ("age", 21)]
dict1 = dict(tuple_list)
print(dict1)
# Convert dictionary keys to a list
print(list(student.keys()))
Summary
✅ Dictionaries store key-value pairs for fast data retrieval.
✅ Keys must be unique and immutable, values can be any data type.
✅ Dictionaries support modification, deletion, and iteration.
✅ Nested dictionaries allow hierarchical data storage.
✅ Dictionary comprehensions enable concise creation of dictionaries.