Dictionary Methods and Comprehensions
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Iterating over key-value pairs and transforming dictionaries is central to processing JSON responses and databases in Python backend development.
Iterating with .items()
Dictionary view is a live window on a dictionary returned by keys(), values() or items(). It shows the current entries without copying them, and you can loop over it or pass it to sum() and len().
Use .items() to unpack both the key and the value simultaneously in a for loop.
salaries = {"Dev": 85000, "Lead": 110000}for role, pay in salaries.items(): print(f"{role}: ${pay:,}")Example 1 · Totalling a price list
prices = {"mouse": 25, "keyboard": 75, "cable": 8}total = 0for name, price in prices.items(): total += priceprint(f"Items: {len(prices)}, total: {total}")print(sum(prices.values()))print(list(prices.keys()))Items: 3, total: 108 108 ['mouse', 'keyboard', 'cable']
What this code does
items()hands the loop one name and one price in each round.prices.values()is a view of just the prices, sosum()adds them without a loop.list(prices.keys())turns the keys view into a normal list.
Iterating over salaries directly (or salaries.keys()) loops only through keys.
Merging dictionaries: the | operator
Dictionary merge is joining two dictionaries into one with the | operator. When both have the same key, the value from the right-hand dictionary wins.
Python 3.9 (PEP 584) introduced the clean union operator | for merging dictionaries.
defaults = {"host": "localhost", "port": 8000}custom = {"port": 5000, "debug": True}config = defaults | customprint(config)Values from the right-hand dictionary (custom) override matching keys in defaults, setting port to 5000.
Dictionary comprehensions
Dictionary comprehension is a one-line way to build a new dictionary from a loop, written as {key: value for item in items}. An optional if at the end keeps only the items you want.
Construct a new dictionary concisely: {key_expr: value_expr for item in iterable if condition}.
names = ["alice", "bob", "charlie"]name_lengths = {name: len(name) for name in names}print(name_lengths)Example 2 · Price list in rupees
products_usd = {"mouse": 25, "keyboard": 75, "cable": 8}# Filter products >= $20 and convert to INR (x83)products_inr = {k: v * 83 for k, v in products_usd.items() if v >= 20}print(products_inr){'mouse': 2075, 'keyboard': 6225}What this code does
- Filters products with price >= 20 (excludes cable).
- Multiplies qualifying prices by 83:
{'mouse': 2075, 'keyboard': 6225}.
Produces {'alice': 5, 'bob': 3, 'charlie': 7}.
Changing entries: update() and setdefault()
setdefault is a dictionary method that returns the value of a key. If the key is missing, it first stores a default value under that key, then returns it. An existing value is never changed.
update() copies the pairs of another dictionary into this one, changing the dictionary in place. setdefault() fills a key only when it is still missing.
profile = {"name": "Leena"}profile.update({"city": "Pune", "name": "Leena S"})profile.setdefault("plan", "free")profile.setdefault("city", "Delhi")print(profile)Example 3 · Filling in missing settings
settings = {"theme": "dark"}settings.setdefault("language", "en")settings.setdefault("theme", "light")settings.update({"font_size": 14})print(settings){'theme': 'dark', 'language': 'en', 'font_size': 14}What this code does
languagewas missing, sosetdefaultstored"en".themealready had a value, sosetdefaultkept"dark".updateaddedfont_sizefrom the small dictionary.
update replaced the name and added the city. setdefault("plan", ...) added a new key, but setdefault("city", ...) left Pune alone because the key existed.
Next step
Check your understanding
9 quick questions