Skip to content
  • Dictionaries · Python

Dictionaries

LearnViaNotes @learnvianotes· 2 min read

dict maps hashable keys to values with average O(1) lookup, insert and delete — the workhorse of Python.

Create, read, update

Python
ages = {"asha": 25, "ravi": 30}
ages["kiran"] = 28                    # insert / update
print(ages["asha"])                   # 25
print(ages.get("zoe"), ages.get("zoe", 0))   # None 0
print("ravi" in ages, len(ages))      # True 3
del ages["ravi"]
print(ages.pop("kiran"), ages)        # 28 {'asha': 25}

Iterating

Python
scores = {"math": 90, "cs": 95}
for subject, score in scores.items():
    print(subject, score, end="; ")   # math 90; cs 95;
print()
print(list(scores), list(scores.values()))   # ['math', 'cs'] [90, 95]

Useful methods

MethodDoes
d.get(k, default)Value or default — never raises
d.setdefault(k, v)Insert v if k is missing, then return d[k]
d.update(other) / d | otherMerge (the right-hand side wins); | returns a new dict (3.9+)
d.pop(k, default)Remove and return
d.items() / keys() / values()Live views that reflect later changes
dict.fromkeys(keys, v)New dict with every key set to v
Python
base = {"theme": "light", "font": 14}
user = {"theme": "dark"}
print(base | user)                        # {'theme': 'dark', 'font': 14}
counts = {}
for ch in "banana":
    counts[ch] = counts.get(ch, 0) + 1
print(counts)                             # {'b': 1, 'a': 3, 'n': 2}
print(max(counts, key=counts.get))        # a

What can be a key?

Keys must be hashable: their hash never changes during their lifetime. Immutable built-ins (int, str, tuple of hashables, frozenset) are hashable; list, dict and set are not.

Python
grid = {(0, 0): "start", (2, 3): "goal"}     # tuples make great coordinate keys
print(grid[(2, 3)])                          # goal
try:
    {[1, 2]: "x"}                            # lists are unhashable
except TypeError as e:
    print(type(e).__name__)                  # TypeError

Dictionary patterns

Python
def two_sum(nums, target):
    seen = {}                      # value → index
    for i, x in enumerate(nums):
        if target - x in seen:
            return [seen[target - x], i]
        seen[x] = i
    return []

print(two_sum([2, 7, 11, 15], 9))   # [0, 1]

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report