Chapter 7: Dictionaries
Master Python dictionaries, a powerful collection type mapping unique, immutable keys to mutable values. Learn lookup syntax, key-value properties, and CRUD mutations.
Why Do We Need Dictionaries?
Instead of accessing elements by positions or integer offsets, we often need to lookup data using descriptive labels. For example, lookup a user profile by username, or search a country by phone code. Python's Dictionaries act as fast key-value maps to make data lookup clean, descriptive, and extremely efficient.
Let's look at dictionary structures, lookup patterns, and custom keys in Python.
7.1 Dictionaries: Keys and Values
A dictionary is a built-in Python collection type. While sequences like lists use consecutive integer indices as coordinates/addresses to locate elements, dictionaries use custom, user-defined labels called keys. Every entry in a dictionary is a key-value pair.
Here are the key properties of dictionaries:
- Keys: Must be unique and of an immutable type (such as strings, integers, or tuples). You cannot use a mutable list as a key.
- Values: Can be of any data type, mutable or immutable, and can contain duplicate values.
Hover or tap on coordinates below to see how lookup addressing differs between integer indexing and labeled key hashing.
7.2 Creating and Indexing Dictionaries
To create a dictionary in Python, we enclose key-value pairs in curly brackets {}. Each key is separated from its value by a colon (:), and individual pairs are separated by commas (,).
To retrieve a value from a dictionary, we use the variable name followed by square brackets with the key inside: dict_name[key]. If the key exists, it returns the mapped value. If it does not exist, Python throws a KeyError.
Click on a key button to visualize how Python processes the lookup and traverses the reference to locate the value in memory.
Try running this code block to verify how to create a dictionary and lookup a value by key:
# Creating a dictionary
release_year_dict = {"Thriller": 1982, "Back in Black": 1980, "The Bodyguard": 1992}
print("Dictionary:", release_year_dict)
# Accessing a value by key
print("Release year of 'Back in Black':", release_year_dict["Back in Black"])
7.3 Mutating Dictionaries: CRUD Operations & Membership
Dictionaries are mutable objects, meaning we can modify them in-place without creating a new dictionary:
- Add or Update: Assign a value to a key using the bracket operator:
album_dict["Graduation"] = 2007. If the key exists, its value is overwritten; if not, a new key-value pair is inserted. - Delete: Use the
delstatement to remove an entry:del album_dict["Thriller"]. - Verify Membership: Use the
inoperator to check if a specific key exists:"Thriller" in album_dict. This checks keys only (not values) and returns a boolean. - Extract collections: Use the
.keys()method to get a list-like view of all keys, and.values()to get all values.
Try running this code block to verify how to add, modify, and delete entries in a dictionary:
release_year_dict = {"Thriller": 1982, "Back in Black": 1980, "The Bodyguard": 1992}
# Adding a new entry
release_year_dict["Graduation"] = 2007
print("After adding Graduation:", release_year_dict)
# Deleting an entry
del release_year_dict["Thriller"]
print("After deleting Thriller:", release_year_dict)
Try running this code block to verify dictionary membership checks and collections extraction:
release_year_dict = {"Back in Black": 1980, "The Bodyguard": 1992, "Graduation": 2007}
# Checking if a key exists
print("Is 'Thriller' in dictionary?", "Thriller" in release_year_dict)
print("Is 'Graduation' in dictionary?", "Graduation" in release_year_dict)
# Getting all keys and values
print("All keys:", list(release_year_dict.keys()))
print("All values:", list(release_year_dict.values()))
Perform adding, deleting, and membership checks dynamically and watch the memory structures update.
Practice Quiz
Test your understanding of Python dictionaries by answering the questions below.