Syntax
{key1: value1, key2: value2}Examples
Creating and Accessing
Building a dictionary and reading values by key.
student = {
"name": "John",
"age": 21,
"course": "Software Engineering"
}
print(student["name"]) # John
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": "John", "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
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference