Python — Dictionaries
Creating dictionaries
Dictionaries store data as key-value pairs:
person = {
"name": "Ada",
"age": 36,
"job": "Engineer"
}
# Empty dictionary
empty = {}
# From a list of tuples
pairs = [("name", "Ada"), ("age", 36)]
person = dict(pairs)
# Using dict() constructor
person = dict(name="Ada", age=36)
Keys must be immutable — strings, numbers, tuples. Values can be anything.
Accessing values
person = {"name": "Ada", "age": 36, "job": "Engineer"}
# Bracket notation
print(person["name"]) # Ada
# .get() — safe access with default
print(person.get("name")) # Ada
print(person.get("email")) # None
print(person.get("email", "N/A")) # N/A
.get() is safer than brackets — it returns None (or a default) instead of raising KeyError.
Modifying dictionaries
person = {"name": "Ada", "age": 36}
# Add or update a key
person["email"] = "ada@example.com"
person["age"] = 37
print(person) # {'name': 'Ada', 'age': 37, 'email': 'ada@example.com'}
# Update multiple keys at once
person.update({"job": "Engineer", "city": "London"})
Removing elements
person = {"name": "Ada", "age": 36, "job": "Engineer"}
# pop — remove and return
age = person.pop("age")
print(age) # 36
print(person) # {'name': 'Ada', 'job': 'Engineer'}
# pop with default
email = person.pop("email", "not found")
# del — remove by key
del person["job"]
# popitem — remove last inserted item
last = person.popitem()
# clear — empty the dictionary
person.clear()
Dictionary methods
person = {"name": "Ada", "age": 36, "job": "Engineer"}
# keys, values, items
print(person.keys()) # dict_keys(['name', 'age', 'job'])
print(person.values()) # dict_values(['Ada', 36, 'Engineer'])
print(person.items()) # dict_items([('name', 'Ada'), ('age', 36), ('job', 'Engineer')])
# Convert to lists
names = list(person.keys())
values = list(person.values())
pairs = list(person.items())
# Check if key exists
print("name" in person) # True
print("email" in person) # False
# Length
print(len(person)) # 3
# Copy
copy = person.copy()
Iterating over dictionaries
person = {"name": "Ada", "age": 36, "job": "Engineer"}
# Iterate over keys (default)
for key in person:
print(key, person[key])
# Iterate over items
for key, value in person.items():
print(f"{key}: {value}")
# Iterate over values
for value in person.values():
print(value)
Dictionary comprehensions
# Create a dictionary from a list
names = ["Ada", "Grace", "Linus"]
name_lengths = {name: len(name) for name in names}
print(name_lengths) # {'Ada': 3, 'Grace': 5, 'Linus': 5}
# Filter
scores = {"Alice": 90, "Bob": 75, "Charlie": 85, "Diana": 95}
high_scores = {name: score for name, score in scores.items() if score >= 85}
print(high_scores) # {'Alice': 90, 'Charlie': 85, 'Diana': 95}
# Transform values
doubled = {k: v * 2 for k, v in scores.items()}
Nested dictionaries
Dictionaries can contain other dictionaries:
students = {
"ada": {
"name": "Ada Lovelace",
"age": 36,
"grades": {"math": 95, "science": 88}
},
"grace": {
"name": "Grace Hopper",
"age": 85,
"grades": {"math": 92, "science": 90}
}
}
# Access nested values
print(students["ada"]["grades"]["math"]) # 95
Common patterns
Counting with defaultdict
from collections import defaultdict
words = "the cat sat on the mat the cat".split()
counts = defaultdict(int)
for word in words:
counts[word] += 1
print(dict(counts)) # {'the': 3, 'cat': 2, 'sat': 1, 'on': 1, 'mat': 1}
Grouping with defaultdict
from collections import defaultdict
students = [
("Alice", "A"), ("Bob", "B"), ("Charlie", "A"),
("Diana", "B"), ("Eve", "A")
]
groups = defaultdict(list)
for name, grade in students:
groups[grade].append(name)
print(dict(groups)) # {'A': ['Alice', 'Charlie', 'Eve'], 'B': ['Bob', 'Diana']}
Merging dictionaries
# Python 3.9+
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1 | dict2 # {'a': 1, 'b': 3, 'c': 4}
# Python 3.5+
merged = {**dict1, **dict2}
Dictionary as a switch/case
def get_day_type(day):
types = {
"Monday": "Weekday",
"Tuesday": "Weekday",
"Wednesday": "Weekday",
"Thursday": "Weekday",
"Friday": "Weekday",
"Saturday": "Weekend",
"Sunday": "Weekend"
}
return types.get(day, "Invalid day")
print(get_day_type("Monday")) # Weekday
The setdefault method
# setdefault — get value or set default if key missing
config = {}
config.setdefault("host", "localhost")
config.setdefault("port", 8080)
print(config) # {'host': 'localhost', 'port': 8080}
# Useful for building lists per key
word_index = {}
for i, word in enumerate(["a", "b", "a", "c", "b", "a"]):
word_index.setdefault(word, []).append(i)
print(word_index) # {'a': [0, 2, 5], 'b': [1, 4], 'c': [3]}
Mini Practice
- Create a dictionary of five countries and their capitals
- Use
.get()to safely access a key that might not exist - Write a dictionary comprehension that maps numbers 1-10 to their squares
- Count the frequency of each letter in a sentence using a dictionary
- Merge two dictionaries and handle duplicate keys by summing values
Next: conditional statements →
Related Topics
Frequently Asked Questions about Dictionaries
What is Dictionaries in Python?
Dictionaries is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Dictionaries?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Dictionaries.
Why is Dictionaries important in Python?
Dictionaries is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.