A dictionary is a built-in Python data structure used to store key-value pairs. Dictionaries are:
- Unordered (before Python 3.7), Ordered (from Python 3.7+)
- Mutable (modifiable)
- Keys must be unique and immutable (strings, numbers, tuples)
- Values can be any data type
1. Creating a Dictionary
Dictionaries are defined using curly braces {}
, with key-value pairs separated by colons :
.
Example: Creating Dictionaries
# Empty dictionary
empty_dict = {}
# Dictionary with data
person = {
"name": "Alice",
"age": 25,
"job": "Engineer"
}
# Dictionary with mixed data types
mixed_dict = {
1: "one",
"two": 2,
(3, 4): "tuple key"
}
print(person)
print(mixed_dict)
Output:
{'name': 'Alice', 'age': 25, 'job': 'Engineer'}
{1: 'one', 'two': 2, (3, 4): 'tuple key'}
2. Accessing Dictionary Elements
Values are accessed using keys (not indexes like lists or tuples).
Example: Accessing Values
person = {"name": "Alice", "age": 25, "job": "Engineer"}
print(person["name"]) # Alice
print(person.get("age")) # 25
Using .get()
to Avoid Errors
print(person.get("salary")) # Returns None instead of an error
Output:
None
3. Modifying a Dictionary
Dictionaries are mutable, allowing you to update, add, or remove elements.
(a) Changing Values
person["age"] = 26
print(person)
Output:
{'name': 'Alice', 'age': 26, 'job': 'Engineer'}
(b) Adding New Key-Value Pairs
person["city"] = "New York"
print(person)
Output:
{'name': 'Alice', 'age': 26, 'job': 'Engineer', 'city': 'New York'}
(c) Removing Elements
del person["job"] # Delete a specific key
print(person)
removed_value = person.pop("city") # Remove and return value
print(removed_value)
person.clear() # Remove all items
print(person)
Output:
{'name': 'Alice', 'age': 26}
New York
{}
4. Looping Through a Dictionary
Dictionaries support different ways of looping.
(a) Looping Through Keys
person = {"name": "Alice", "age": 25, "job": "Engineer"}
for key in person:
print(key) # Prints keys
Output:
name
age
job
(b) Looping Through Values
for value in person.values():
print(value)
Output:
Alice
25
Engineer
(c) Looping Through Key-Value Pairs
for key, value in person.items():
print(key, ":", value)
Output:
name : Alice
age : 25
job : Engineer
5. Dictionary Methods
Method | Description |
---|---|
keys() | Returns all keys |
values() | Returns all values |
items() | Returns key-value pairs |
get(key) | Gets the value for a key |
pop(key) | Removes key and returns value |
update(dict) | Updates dictionary with another dictionary |
clear() | Removes all elements |
Example: Using Dictionary Methods
person = {"name": "Alice", "age": 25}
print(person.keys()) # dict_keys(['name', 'age'])
print(person.values()) # dict_values(['Alice', 25])
print(person.items()) # dict_items([('name', 'Alice'), ('age', 25)])
person.update({"age": 26, "city": "New York"})
print(person) # {'name': 'Alice', 'age': 26, 'city': 'New York'}
6. Checking if a Key Exists
if "age" in person:
print("Age key exists!")
Output:
Age key exists!
7. Nested Dictionaries
A dictionary can contain another dictionary.
Example: Nested Dictionary
students = {
"Alice": {"age": 25, "grade": "A"},
"Bob": {"age": 24, "grade": "B"}
}
print(students["Alice"]["grade"]) # A
8. Dictionary Comprehensions
Similar to list comprehensions, dictionary comprehensions create dictionaries in a compact way.
Example: Creating a Dictionary Using Comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
9. Merging Two Dictionaries
From Python 3.9+, dictionaries can be merged using |
.
Example: Merging Dictionaries
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged_dict = dict1 | dict2
print(merged_dict)
Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
For older Python versions:
pythonCopyEditdict1.update(dict2)
print(dict1)
10. Copying a Dictionary
To avoid modifying the original dictionary, use copy()
.
original = {"name": "Alice", "age": 25}
copy_dict = original.copy()
copy_dict["age"] = 26
print(original) # {'name': 'Alice', 'age': 25}
print(copy_dict) # {'name': 'Alice', 'age': 26}
11. Removing Duplicates from a Dictionary
Using dictionary comprehension:
data = {"a": 1, "b": 2, "c": 1, "d": 3}
unique_values = {k: v for k, v in data.items() if list(data.values()).count(v) == 1}
print(unique_values)
Output:
{'b': 2, 'd': 3}
12. When to Use a Dictionary?
Use dictionaries when:
- You need key-value pairs (e.g., storing user data).
- You want fast lookups (dictionaries are optimized for this).
- You need unordered but structured data.
Avoid dictionaries when:
- Order matters and you want sequential access (use lists).
- Keys may change frequently (keys must be immutable).