Syntax
{key1: value1, key2: value2}Examples
Creating and Accessing
Building a dictionary and reading values by key.
student = {
"name": "Fola",
"age": 21,
"course": "Software Engineering"
}
print(student["name"]) # Fola
print(student.get("age")) # 21
print(student.get("gpa", 0.0)) # 0.0 (default, since 'gpa' doesn't exist)Adding, Updating, and Removing Keys
Dictionaries are mutable - keys can be added, changed, or deleted after creation.
student = {"name": "Fola", "age": 21}
student["gpa"] = 3.8 # add a new key
student["age"] = 22 # update an existing key
print(student)
del student["gpa"] # remove a key
print(student)
age = student.pop("age") # remove and return the value
print(age, student)Dictionary Methods
Common methods for inspecting a dictionary's contents.
scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
print(list(scores.keys())) # ['Alice', 'Bob', 'Charlie']
print(list(scores.values())) # [85, 92, 78]
print(list(scores.items())) # [('Alice', 85), ('Bob', 92), ('Charlie', 78)]
for name, score in scores.items():
print(f"{name}: {score}")Merging Dictionaries
Combining two dictionaries, with keys in the second overriding duplicates in the first.
defaults = {"theme": "light", "font_size": 12}
overrides = {"font_size": 16, "language": "en"}
# Python 3.9+ merge operator
merged = defaults | overrides
print(merged) # {'theme': 'light', 'font_size': 16, 'language': 'en'}
# Older, equally valid approach
merged2 = {**defaults, **overrides}
print(merged2)Best practices
- Use .get(key, default) instead of square brackets when a key might not exist, to avoid a KeyError
- Use the | merge operator (Python 3.9+) or {**a, **b} for combining dictionaries without a loop
- Iterate with .items() when you need both keys and values, rather than looking up dict[key] inside a loop over keys
- Use dictionaries for structured records with named fields, and lists of dictionaries for collections of records
- Remember dictionary keys must be hashable - lists cannot be used as keys, but tuples can
At a glance
- Purpose
- Scripting and general-purpose applications
- File extension
- .py
- Runs in
- Python interpreter
- Usually used with
- Python standard library and packages
Specifications & further reading
Related Python documentation
Lists
A list is Python's built-in ordered, mutable collection type, created with square brackets. Lists can hold items of any type - even a mix of types - and support indexing, slicing, and a wide range of built-in methods for adding, removing, and reordering elements. Because they are mutable, lists can be changed in place after creation, which makes them the go-to structure for collections that grow or shrink over time.Tuples
A tuple is an ordered, immutable collection, created with parentheses (or often just commas). Once created, a tuple's contents cannot be changed, added to, or removed - this immutability makes tuples faster than lists and safe to use as dictionary keys or in sets. Tuples are commonly used for fixed collections of related values, like coordinates or RGB colors, and for returning multiple values from a function.Sets
A set is an unordered collection of unique, hashable items, created with curly braces or the set() function. Sets automatically eliminate duplicates and support fast membership testing, along with mathematical set operations like union, intersection, and difference. They're especially useful for deduplicating data and for comparing two collections to find overlaps or differences.List Comprehensions
A list comprehension is a concise, expressive way to build a new list by applying an expression to every item in an iterable, optionally filtering with a condition. It replaces the common pattern of creating an empty list and appending to it inside a for loop, condensing that logic into a single readable line. Comprehensions are considered idiomatic Python for simple to moderately complex transformations.
A list is Python's built-in ordered, mutable collection type, created with square brackets. Lists can hold items of any type - even a mix of types - and support indexing, slicing, and a wide range of built-in methods for adding, removing, and reordering elements. Because they are mutable, lists can be changed in place after creation, which makes them the go-to structure for collections that grow or shrink over time.Tuples
A tuple is an ordered, immutable collection, created with parentheses (or often just commas). Once created, a tuple's contents cannot be changed, added to, or removed - this immutability makes tuples faster than lists and safe to use as dictionary keys or in sets. Tuples are commonly used for fixed collections of related values, like coordinates or RGB colors, and for returning multiple values from a function.Sets
A set is an unordered collection of unique, hashable items, created with curly braces or the set() function. Sets automatically eliminate duplicates and support fast membership testing, along with mathematical set operations like union, intersection, and difference. They're especially useful for deduplicating data and for comparing two collections to find overlaps or differences.List Comprehensions
A list comprehension is a concise, expressive way to build a new list by applying an expression to every item in an iterable, optionally filtering with a condition. It replaces the common pattern of creating an empty list and appending to it inside a for loop, condensing that logic into a single readable line. Comprehensions are considered idiomatic Python for simple to moderately complex transformations.