Dictionary Methods Examples
Short, runnable programs that show python dictionary methods in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Dictionary Methods lesson.
1Reading settings with get()
get() supplies a fallback for missing keys, including one level down in a nested dictionary. Notice that the value 0 for volume is kept: config.get("volume") or 50 would wrongly replace it, because 0 is falsy.
config = {"theme": "dark", "volume": 0, "user": {"name": "Asha"}}
print(config.get("theme", "light"))
print(config.get("volume", 50), config.get("volume") or 50)
print(config.get("language", "en"))
print(config["user"].get("email", "no email"))
print(config.get("profile", {}).get("city", "unknown"))Expected outputdark
0 50
en
no email
unknown
2Grouping support tickets by priority
setdefault() creates each priority's list on first use. When reading, get(level, []) gives an empty list for a priority nobody used, so the loop never raises a KeyError.
tickets = [
("login bug", "high"),
("typo", "low"),
("crash", "high"),
("slow page", "medium"),
("logo", "low"),
]
by_priority = {}
for title, level in tickets:
by_priority.setdefault(level, []).append(title)
for level in ("high", "medium", "low", "urgent"):
print(level, "->", by_priority.get(level, []))Expected outputhigh -> ['login bug', 'crash']
medium -> ['slow page']
low -> ['typo', 'logo']
urgent -> []
3Layered settings with the | operator
Each | builds a new dictionary and the right-hand side wins, so listing the sources from weakest to strongest gives the final settings. The defaults dictionary is left untouched, while |= changes settings in place. ({**a, **b} does the same as a | b in older Python versions.)
defaults = {"theme": "light", "font": 14, "autosave": True}
system = {"font": 16}
user = {"theme": "dark", "autosave": False}
settings = defaults | system | user
print(settings)
print(defaults)
settings |= {"font": 20}
print(settings["font"], defaults["font"])Expected output{'theme': 'dark', 'font': 16, 'autosave': False}
{'theme': 'light', 'font': 14, 'autosave': True}
20 14
4What changed between two price lists?
Key views behave like sets. old.keys() - new.keys() finds removed items, the reverse finds new ones, and & finds the items present in both, which you can then compare value by value.
old = {"tea": 3, "cake": 4, "juice": 2}
new = {"tea": 3, "cake": 5, "milk": 2}
print("Removed:", sorted(old.keys() - new.keys()))
print("Added:", sorted(new.keys() - old.keys()))
for item in sorted(old.keys() & new.keys()):
if old[item] != new[item]:
print(item, "changed from", old[item], "to", new[item])Expected outputRemoved: ['juice']
Added: ['milk']
cake changed from 4 to 5
5Building, filtering and inverting dictionaries
zip pairs two lists, a comprehension swaps keys and values, fromkeys sets up starting counters, and a comprehension with if filters. Inverting is safe here because all the country names are different.
codes = ["IN", "JP", "KE"]
countries = ["India", "Japan", "Kenya"]
by_code = dict(zip(codes, countries))
print(by_code)
by_name = {name: code for code, name in by_code.items()}
print(by_name["Japan"])
medals = dict.fromkeys(codes, 0)
medals["KE"] += 5
print(medals)
population = {"IN": 1400, "JP": 125, "KE": 55}
big = {code: size for code, size in population.items() if size > 100}
print(big)Expected output{'IN': 'India', 'JP': 'Japan', 'KE': 'Kenya'}
JP
{'IN': 0, 'JP': 0, 'KE': 5}
{'IN': 1400, 'JP': 125}
6Removing entries safely
Looping over list(sessions) is a snapshot, so deleting inside the loop is allowed. pop() with a default handles a key that may already be gone, and popitem() takes the most recently added pair.
sessions = {"a1": 5, "b2": 0, "c3": 9, "d4": 0}
for token in list(sessions):
if sessions[token] == 0:
del sessions[token]
print(sessions)
print(sessions.pop("zzz", "already logged out"))
print(sessions.pop("a1"))
print(sessions.popitem())
print(sessions)Expected output{'a1': 5, 'c3': 9}
already logged out
5
('c3', 9)
{}
Practise next
Python Dictionary Methods exercises → Back to the lesson
Python Dictionaries examplesPython Nested Data Structures examplesPython collections Module examplesPython KeyError: What It Means and How to Fix It examples