Python Tutorial for Beginners 5: Dictionaries - Working with Key-Value Pairs
Based on Corey Schafer's video on YouTube. If you like this content, support the original creators by watching, liking and subscribing to their content.
Dictionaries store records as key–value pairs, enabling fast lookup by a unique key.
Briefing
Python dictionaries store data as key–value pairs, letting programmers look up values by a unique key—similar to how a physical dictionary maps words to definitions. In the student example, a single dictionary holds multiple fields: a name string, an age integer, and courses as a list. Keys are typically strings (or integers), and values can be “anything” (strings, numbers, lists, and more), which makes dictionaries a flexible way to model real-world records.
Accessing data is straightforward: square-bracket indexing retrieves the value for a given key. Using student["name"] returns the name value, while student["courses"] returns the list of courses. If a key doesn’t exist, direct indexing raises a KeyError, which can be undesirable when missing data is expected.
To handle absent keys safely, the dictionary get method provides a default behavior. Calling student.get("phone") returns None when the key is missing, avoiding an exception. Passing a second argument to get lets code return a custom fallback, such as student.get("phone", "not found"), which yields “not found” instead of None.
Dictionaries also support adding and updating entries. Assigning a new key—such as student["phone"] = "5555555"—inserts that key/value pair into the dictionary. Reassigning an existing key updates its value, demonstrated by changing the name from John to Jane. For updating multiple fields at once, the update method accepts another dictionary and merges it into the original, overwriting existing keys and adding new ones. In the example, update changes name to Jane, sets age to 26, and adds the phone key in a single call.
Removing data is handled in two common ways. The del keyword deletes a specific key/value pair without returning anything; deleting student["age"] leaves only the remaining keys. The pop method removes a key/value pair and returns the removed value, enabling code to capture it—such as age = student.pop("age"), which both deletes the age entry and stores the removed number.
Finally, dictionaries can be inspected and iterated over. len(student) returns the number of keys. student.keys() lists all keys, student.values() lists all values, and student.items() returns key–value pairs. Iterating directly over a dictionary yields keys only, so looping through student.items() is the practical approach when both keys and values are needed. The loop structure uses two loop variables (key, value) to process each pair cleanly.
Taken together, these operations—lookup, safe retrieval with get, insertion/update with assignment and update, deletion with del or pop, and iteration with items—form the core toolkit for working with dictionaries in Python, setting up the next step toward conditionals and boolean logic.
Cornell Notes
Dictionaries in Python map unique keys to values, making them ideal for representing records like a student with fields such as name, age, courses, and phone. Values can be different types (strings, integers, lists), while keys are usually strings or integers and must be immutable. Direct key access with square brackets raises a KeyError when a key is missing, but the get method avoids that by returning None or a specified default. Dictionaries can be modified by assigning new keys, updating existing ones, or using update to change multiple fields at once. Deletion uses del (no return) or pop (returns the removed value), and iteration uses items() to loop over both keys and values.
How does a dictionary represent a real-world record like a student, and what roles do keys and values play?
What’s the practical difference between using square brackets vs dict.get() when a key might not exist?
How can code add a new dictionary entry or update an existing one?
When should update() be used instead of multiple individual assignments?
What are the two main ways to delete entries, and how do they differ?
How do you iterate over both keys and values in a dictionary?
Review Questions
- What happens when you access a missing key with square brackets, and how does dict.get() change that behavior?
- Write the code to add a new key "phone" to a dictionary called student and then retrieve it safely with a default of "not found".
- Which dictionary method returns key–value pairs suitable for looping, and what loop variables does it provide?
Key Points
- 1
Dictionaries store records as key–value pairs, enabling fast lookup by a unique key.
- 2
Square-bracket access (student["name"]) retrieves values but raises KeyError for missing keys.
- 3
dict.get(key) returns None for missing keys, and dict.get(key, default) returns a custom fallback.
- 4
Assigning student["phone"] = "5555555" adds new entries, while reassigning an existing key updates its value.
- 5
dict.update(other_dict) updates multiple keys in one operation, overwriting existing keys and adding new ones.
- 6
del removes a key/value pair without returning it, while pop removes and returns the deleted value.
- 7
Use len(), keys(), values(), and items() to inspect dictionaries; iterate over items() to get both keys and values.