Dictionaries: Key-Value Pairs
Introduction to Dictionaries
A dictionary is a fast, flexible container that maps unique keys to values. Unlike lists, which are indexed by numbers (0, 1, 2...), dictionaries are indexed by keys, which can be strings, numbers, or even tuples. They are the backbone of data representation in Python.
Python# A simple contact book contacts = { "Alice": "555-1234", "Bob": "555-9876" } # Lookup by name (key) print(contacts["Alice"]) # "555-1234"
Dictionary Visualization
Key (Name) β Value (Phone)Creating Dictionaries
You can create dictionaries using the literal syntax {} or the dict() constructor. The literal syntax is faster and more common.
Python# Literal syntax (Recommended) student = {"name": "Alice", "age": 25} # dict() constructor car = dict(brand="Toyota", model="Corolla") # Empty dictionary empty = {}
Dictionary Visualization
student = {...}Accessing Values
Access values using square brackets [key]. If you're unsure if a key exists, use .get(key) to avoid errors. .get() returns None (or a default) if the key is missing.
Pythonstudent = {"name": "Alice", "age": 25} # Direct access print(student["name"]) # "Alice" # print(student["grade"]) # KeyError! # Safe access with .get() grade = student.get("grade") # None score = student.get("score", 0) # 0 (default)
Dictionary Visualization
student.get("name") β "Alice"Updating & Adding
Dictionaries are mutable. Assign a value to a key to add it (if new) or update it (if it exists).
Pythonstudent = {"name": "Alice", "age": 25} # Add new key student["grade"] = "A" # Update existing key student["age"] = 26 print(student) # {'name': 'Alice', 'age': 26, 'grade': 'A'}
Dictionary Visualization
Modified age, added gradeRemoving Items
Use .pop(key) to remove a key and return its value. 'del' deletes a key without returning. .popitem() removes the last inserted item (LIFO). .clear() wipes the dictionary.
Pythonstudent = {"name": "Alice", "age": 26, "grade": "A"} # Remove and get value grade = student.pop("grade") # "A" # Delete specific key del student["age"] # Remove last item item = student.popitem() # ('name', 'Alice') print(student) # {}
Dictionary Visualization
After popping 'grade'Iteration
You can loop over a dictionary's keys, values, or both. Looping over the dictionary directly yields keys.
Pythondata = {"a": 1, "b": 2} # Loop over keys (default) for key in data: print(key) # "a", "b" # Loop over keys and values for key, val in data.items(): print(f"{key}: {val}")
Dictionary Visualization
for k, v in data.items()Dictionary Methods
.keys(), .values(), and .items() return view objects. These views update dynamically if the dictionary changes.
Pythond = {"x": 10, "y": 20} keys = d.keys() # dict_keys(['x', 'y']) vals = d.values() # dict_values([10, 20]) items = d.items() # dict_items([('x', 10), ('y', 20)])
Dictionary Visualization
.keys(), .values(), .items()Nested Dictionaries
Dictionaries can contain other dictionaries. This is great for representing complex hierarchical data like JSON responses or database records.
Pythonstudents = { "Alice": {"age": 25, "grade": "A"}, "Bob": {"age": 22, "grade": "B"} } # Access nested value print(students["Alice"]["grade"]) # "A"
Real-World Examples
Dictionaries are everywhere: user profiles, configuration settings, counting frequencies, and caching results.
Python# 1. Frequency Counter text = "apple banana apple" counts = {} for word in text.split(): counts[word] = counts.get(word, 0) + 1 # {'apple': 2, 'banana': 1} # 2. Config Settings config = { "theme": "dark", "notifications": True, "volume": 80 }
Dictionary Visualization
Word frequency countMaster this concept
Hands-on practice is the fastest way to learn. Head over to our interactive workspace to solve this topic's challenge.
Visual Lab
Dictionary Visualization
student = {'name': 'Alice', ...}New Challenge available!
Master Dictionaries: Key-Value Pairs with a hands-on task.