Python Dictionaries
What is a Python Dictionary?
A dictionary is a collection which is unordered, changeable (mutable), and does not allow duplicates.
A dictionary in Python is a collection of key-value pairs. It is:
- Unordered (Python 3.6+ keeps insertion order)
- Changeable (Mutable)
- Indexed by keys
- No duplicate keys
Dictionaries are written with curly brackets, and they have keys and values:
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(my_dict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Accessing Items
Access dictionary items by referring to their key:
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(my_dict["model"])
Use .get()
method for safe access:
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(my_dict.get("year"))
Dictionary Keys
You can return the list of all keys using .keys()
:
To check if a key exists:
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in my_dict:
print("Model key is present.")
Dictionary Values
Get all values in the dictionary:
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(my_dict.values())
Output
dict_values(['Ford', 'Mustang', 1964])
Dictionary Items
Get all key-value pairs as tuples:
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(my_dict.items())
Output
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
Add Dictionary Items
Add a new key-value pair:
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
my_dict["color"] = "red"
print(my_dict)
Output
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Change Dictionary Items
Update an existing item:
my_dict["year"] = 2024
Or use .update()
method:
my_dict.update({"year": 2025})
Remove Dictionary Items
Remove by key:
my_dict.pop("model")
Remove last inserted item:
my_dict.popitem()
Remove a key using del
:
del my_dict["brand"]
Clear all items:
my_dict.clear()
Loop Through Dictionaries
Loop through keys:
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for key in my_dict:
print(key)
Output
brand
model
year
Loop through values:
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for value in my_dict.values():
print(value)
Output
Ford
Mustang
1964
Loop through key-value pairs:
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for key, value in my_dict.items():
print(key, "=", value)
Output
brand = Ford
model = Mustang
year = 1964
Copy a Dictionary
Use copy()
or dict()
:
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = my_dict.copy()
y = dict(my_dict)
Nested Dictionaries
A dictionary can contain other dictionaries:
my_family = {
"child1": {"name": "Alice", "age": 10},
"child2": {"name": "Bob", "age": 12}
}
print(my_family["child1"]["name"])
Output
Alice
Dictionary Constructor
You can also create dictionaries using the dict()
constructor:
car = dict(brand="Ford", model="Mustang", year=1964)
print(car)
Output
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Python Dictionary Methods
Method | Description |
---|---|
clear() | Removes all elements |
copy() | Returns a shallow copy |
fromkeys() | Returns a dictionary with specified keys |
get() | Returns the value of the specified key |
items() | Returns key-value pair tuples |
keys() | Returns a list of keys |
pop() | Removes item with specified key |
popitem() | Removes the last inserted item |
setdefault() | Returns the value of key, inserts if absent |
update() | Updates the dictionary with new key-values |
values() | Returns all values in the dictionary |
Example 1: Creating a Dictionary
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Explanation: We created a dictionary with 3 key-value pairs. Each key (like "brand"
) is associated with a value (like "Ford"
).
Example 2: Accessing Items
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car["model"]) # Using key directly
print(car.get("year")) # Using get() method
Output:
Mustang
1964
Explanation: The car["model"]
fetches the value for the key "model"
, and get("year")
does the same with safer handling if the key doesn't exist.
Example 3: Change Values
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car["year"] = 2024
print(car)
Output
{'brand': 'Ford', 'model': 'Mustang', 'year': 2024}
Explanation: The value for the key "year"
is updated from 1964
to 2024
.
Example 4: Adding Items
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car["color"] = "red"
print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2024, 'color': 'red'}
Explanation: A new key "color"
is added to the dictionary with the value "red"
.
Example 5: Loop Through Dictionary
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for key, value in car.items():
print(key, ":", value)
Output:
brand : Ford
model : Mustang
year : 2024
color : red
Explanation: .items()
returns both key and value so we can print them in a loop.
Example 6: Check if Key Exists
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in car:
print("Yes, 'model' is a key.")
Output:
Yes, 'model' is a key.
Explanation: Checks for the presence of a specific key in the dictionary.
Example 7: Remove Items
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.pop("color")
print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2024}
Explanation: .pop()
removes a key and its value.
Example 8: Dictionary Length
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(len(car))
Output:
3
Explanation: len()
returns the number of key-value pairs in the dictionary.
Example 9: Copy a Dictionary
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car_copy = car.copy()
print(car_copy)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2024}
Explanation: .copy()
creates a shallow copy of the dictionary.
Example 10: Nested Dictionaries
family = {
"child1": {"name": "Alice", "age": 10},
"child2": {"name": "Bob", "age": 12}
}
print(family["child1"]["name"])
Output:
Alice
Explanation: This is a dictionary within a dictionary. Access nested data using multiple keys.
Example 11: Dictionary Comprehension
squares = {x: x*x for x in range(1, 6)}
print(squares)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Explanation: This is a compact way to create a dictionary using a loop.
Example 12: Dictionary Methods Summary
d = {"a": 1, "b": 2}
print(d.keys()) # dict_keys(['a', 'b'])
print(d.values()) # dict_values([1, 2])
print(d.items()) # dict_items([('a', 1), ('b', 2)])
print(d.get("a")) # 1
d.update({"c": 3})
print(d) # {'a': 1, 'b': 2, 'c': 3}
Conclusion
Dictionaries are one of Python’s most useful and flexible data structures. They’re perfect for representing real-world structured data like user profiles, configurations, JSON-like objects, and more.