Lesson 19 of 34 · Dictionaries & Sets
Python Dictionaries: Keys, Values and Methods
Lists find things by position. But often you want to find things by name: the price of a potion, the score of a player, the definition of a word. Python's dictionary (dict) stores key → value pairs and finds any value by its key almost instantly, no matter how big the dictionary grows.
Creating and reading a dictionary
Write a dictionary with curly braces and key: value pairs:
hero = {"name": "Ada", "level": 3, "class": "wizard"}
prices = {"potion": 5, "rope": 2}
empty = {}
print(hero["name"]) # Ada
print(len(hero)) # 3
print(hero["mana"]) # KeyError: 'mana'
Square brackets look up a key and raise KeyError if it's missing.
Safe lookups with get()
get() returns None — or a default you choose — instead of raising an error:
print(hero.get("mana")) # None
print(hero.get("mana", 0)) # 0
Adding, updating and removing
hero["level"] = 4 # update an existing key
hero["mana"] = 30 # add a new key
hero.update({"level": 5, "guild": "Owls"}) # several at once
removed = hero.pop("guild") # remove a key and return its value
del hero["mana"] # remove a key (KeyError if missing)
Keys are unique: assigning to an existing key replaces its value. The | operator merges two dictionaries into a new one, with the right side winning on conflicts: defaults | settings.
Checking for keys
in checks keys, not values:
print("name" in hero) # True
print("Ada" in hero) # False
print("Ada" in hero.values()) # True
Looping over a dictionary
prices = {"potion": 5, "rope": 2, "map": 15}
for item in prices: # keys
print(item)
for price in prices.values(): # values
print(price)
for item, price in prices.items(): # (key, value) pairs
print(f"{item} costs {price} gold")
Dictionaries remember insertion order, so loops visit keys in the order they were added.
Two essential patterns
Counting — get() with a default of 0 handles keys you haven't seen yet:
counts = {}
for color in ["red", "blue", "red"]:
counts[color] = counts.get(color, 0) + 1
print(counts) # {'red': 2, 'blue': 1}
Grouping — setdefault() returns the value for a key, inserting a default first if the key is missing:
groups = {}
for word in ["apple", "avocado", "banana"]:
groups.setdefault(word[0], []).append(word)
print(groups) # {'a': ['apple', 'avocado'], 'b': ['banana']}
The standard library's collections.Counter and collections.defaultdict package these patterns up for you — worth exploring once you're comfortable with the basics.
What can be a key?
Keys must be immutable (strictly, hashable): strings, numbers and tuples work; lists don't. {[1, 2]: "x"} raises TypeError: cannot use 'list' as a dict key (unhashable type: 'list'). Values can be anything, including lists and other dictionaries.
Common mistakes
KeyErrorwhen a key may be missing — useget()or check withinfirst.- Changing a dictionary's size while looping over it raises
RuntimeError: dictionary changed size during iteration. Loop over a copy, such aslist(d), instead. - Expecting
into search values — it only checks keys. - Accidental sharing:
b = adoesn't copy a dictionary. Usedict(a)ora.copy().
Assignment
Write three functions:
count_words(text)returns a dictionary mapping each word to the number of times it appears. Words are separated by whitespace and counted case-insensitively (store them lowercase). Empty text gives{}.invert(mapping)returns a new dictionary with keys and values swapped. You can assume all values are unique.merge_inventory(a, b)returns a new dictionary containing the items of both inventories. When an item appears in both, add the counts together. Neither input may be modified.
count_words("the cat and the hat")
# {"the": 2, "cat": 1, "and": 1, "hat": 1}
invert({"a": 1, "b": 2})
# {1: "a", 2: "b"}
merge_inventory({"potion": 2, "arrow": 10}, {"potion": 1, "rope": 1})
# {"potion": 3, "arrow": 10, "rope": 1}Premium lesson
Unlock the full Learn Python course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Maps and dictionaries in other languages
- JavaScript Map and Set · JavaScript
- Go Maps: Create, Read, Update, Delete and comma-ok · Go
- Java HashMap: Key-Value Pairs · Java
- C# Dictionary<TKey, TValue> · C#
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .