Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered, changeable, and does NOT allow duplicates.
Dictionaries are written with curly brackets {}, and have keys and values separated by colons :.
- Ordered: As of Python 3.7, dictionaries are ordered (the items have a defined order).
- Changeable (Mutable): We can change, add, or remove items after the dictionary has been created.
- No Duplicates: Dictionaries cannot have two items with the exact same key. The second key will simply overwrite the first one!
Tip
Real-World Examples:
- User Profiles: Web applications heavily rely on dictionaries (often formatted as JSON) to store data. A dictionary is highly mutable, meaning users can update their profile information at any time. It perfectly maps properties (keys) to their respective data (values). Because it enforces no duplicate keys, a user cannot accidentally have two different "username" properties assigned to them at the same time! Since Python 3.7, it is also strictly ordered, meaning the profile properties are consistently returned in the exact sequence they were added.
- Lightning-Fast Lookups (Phonebooks): If you need to search a List of 1,000,000 items to find a specific person, Python has to check every single item one-by-one. A dictionary uses a concept called "Hashing" to map a unique, non-repeating key (a person's name) directly to their value (their phone number). This guarantees no duplicate keys exist, and allows Python to bypass searching entirely to find the exact data instantly, no matter how massive the dictionary gets! It also remains highly mutable so you can easily update a friend's phone number when they move.
Input:
# Creating a dictionary
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car)
print("Length of dictionary:", len(car))Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Length of dictionary: 3
A dictionary key must be an immutable (hashable) object.
- Allowed Keys: Strings, numbers (int, float), and tuples (only if they contain immutable objects).
- Disallowed Keys: Lists, dictionaries, or sets. Attempting to use a mutable sequence as a key will raise a
TypeError: unhashable type.
Input:
# 1. Valid keys: integers and strings
data1 = {101: "Alpha", "name": "Beta"}
print("data1 created successfully.")
# 2. Invalid key: list (mutable)
try:
data2 = {[1, 2]: "coordinates"}
except TypeError as e:
print("TypeError raised:", e)Output:
data1 created successfully.
TypeError raised: unhashable type: 'list'
If you accidentally use the same key twice, Python will just silently overwrite the old value with the new value.
Input:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020 # This overwrites the 1964 value!
}
print(car)Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
You can access the items of a dictionary by referring to its key name, inside square brackets [].
Input:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car["model"]
print("The car model is:", x)Output:
The car model is: Mustang
You can also use the .get() method. The advantage of .get() is that if the key does not exist, it will return None instead of completely crashing your program with a KeyError!
Input:
# Using get() to prevent crashes
print("Brand:", car.get("brand"))
# Trying to get a key that doesn't exist
print("Color:", car.get("color"))
# print(car["color"]) # This would throw a KeyError and crash!Output:
Brand: Ford
Color: None
Python provides three powerful methods to grab all the data out of a dictionary as lists (technically, "view objects").
keys(): Returns a list of all the keys.values(): Returns a list of all the values.items(): Returns a list of all the(key, value)tuples!
Input:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print("All Keys:", car.keys())
print("All Values:", car.values())
print("All Items:", car.items())Output:
All Keys: dict_keys(['brand', 'model', 'year'])
All Values: dict_values(['Ford', 'Mustang', 1964])
All Items: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
When used on a dictionary, any() and all() check the truthfulness of the KEYS, not the values!
all()returnsTrueif all keys in the dictionary are true (or if the dictionary is empty).any()returnsTrueif any key in the dictionary is true.
Input:
# Here, the keys are 0 and 1. (0 is False, 1 is True)
test_dict = {
0: "Apple",
1: "Banana"
}
print("Are all keys true?", all(test_dict))
print("Are any keys true?", any(test_dict))Output:
Are all keys true? False
Are any keys true? True