Python Dictionary Tutorial - keys, values, items Methods
What is a Dictionary?
A dictionary stores data as key-value pairs. Keys must be unique and immutable (strings, numbers, tuples). Values can be anything. Dictionaries are ordered as of Python 3.7+.
Creating Dictionaries
empty = {}
person = {"name": "Alice", "age": 25, "city": "London"}
# dict() constructor
config = dict(host="localhost", port=5432, debug=True)
# From list of tuples
pairs = dict([("a", 1), ("b", 2), ("c", 3)])
# Nested dictionary
student = {
"name": "Bob",
"grades": {"math": 90, "english": 85},
"hobbies": ["coding", "reading"]
}
print(type(person)) # <class 'dict'>
print(len(person)) # 3
Accessing & Modifying
person = {"name": "Alice", "age": 25, "city": "London"}
# Access by key
print(person["name"]) # Alice
print(person.get("age")) # 25
print(person.get("email")) # None (no KeyError)
print(person.get("email", "N/A")) # N/A (default value)
# Modify
person["age"] = 26 # update existing
person["email"] = "alice@example.com" # add new key
# Delete
del person["city"]
removed = person.pop("email") # removes and returns value
print(removed) # alice@example.com
# Nested access
student = {"grades": {"math": 90, "english": 85}}
print(student["grades"]["math"]) # 90
Iterating Dictionaries
scores = {"Alice": 95, "Bob": 87, "Charlie": 92}
# Iterate keys (default)
for name in scores:
print(name)
# Iterate values
for score in scores.values():
print(score)
# Iterate key-value pairs
for name, score in scores.items():
print(f"{name}: {score}")
# Check key existence
if "Alice" in scores:
print("Alice found!")
# Dict comprehension
squared = {x: x**2 for x in range(1, 6)}
print(squared) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Filter with comprehension
high_scores = {k: v for k, v in scores.items() if v >= 90}
print(high_scores) # {'Alice': 95, 'Charlie': 92}
Dictionary Methods
| Method | Description |
|---|---|
get(key, default) | Return value or default (no KeyError) |
keys() | Return all keys |
values() | Return all values |
items() | Return all key-value pairs as tuples |
update(d) | Merge another dict into this one |
pop(key) | Remove and return value by key |
popitem() | Remove and return last inserted pair |
setdefault(key, val) | Return value; set if key missing |
clear() | Remove all items |
copy() | Return shallow copy |
fromkeys(keys, val) | Create dict from keys with same value |
d = {"a": 1, "b": 2}
# update - merge dicts
d.update({"c": 3, "d": 4})
print(d) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Merge with | operator (Python 3.9+)
d1 = {"x": 1}
d2 = {"y": 2}
merged = d1 | d2
print(merged) # {'x': 1, 'y': 2}
# setdefault - add key only if it doesn't exist
counts = {}
for char in "hello":
counts.setdefault(char, 0)
counts[char] += 1
print(counts) # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
# fromkeys
keys = ["name", "age", "email"]
template = dict.fromkeys(keys, None)
print(template) # {'name': None, 'age': None, 'email': None}
# Sorting a dict by value
scores = {"Alice": 95, "Bob": 87, "Charlie": 92}
sorted_scores = dict(sorted(scores.items(), key=lambda x: x[1], reverse=True))
print(sorted_scores) # {'Alice': 95, 'Charlie': 92, 'Bob': 87}
Level Up Your Python Skills
Master Python with these hand-picked resources
10,000+ learners
Free forever
Updated 2026
Key Takeaways
- Dictionaries store key-value pairs. Keys must be hashable (strings, numbers, tuples).
- Access: dict[key] raises KeyError if missing. Use dict.get(key, default) for safe access.
- dict.items() returns key-value pairs; dict.keys() returns keys; dict.values() returns values.
- Dictionary comprehension: {k: v for k, v in items if condition}
- Merge dicts in Python 3.9+: merged = dict1 | dict2. Update: dict1 |= dict2.
- defaultdict from collections auto-creates missing keys with a default factory.
- OrderedDict preserves insertion order (regular dicts do too in Python 3.7+).
Frequently Asked Questions
Related Python Topics