Legends ofPythos
Claim your name
Working with Data

Dictionaries in depth

Lesson 5 of 14

Watch the lesson1:20 · with Torsten
Think of a dictionary as a row of labelled drawers in an office filing cabinet. You do not count how many steps to take down the hall; you walk straight to the label and open it. That is why dictionaries are fast for lookups: Python uses the key directly, skipping any intermediate items.
You will use this pattern when processing real data like user profiles, sensor logs, or word frequencies in text analysis. Instead of searching through a list to find 'carol', you ask the dictionary directly and get her score instantly.

Looping over items

scores = {'alice': 85, 'bob': 92}
for name, score in scores.items():
    print(f'{name}: {score}')
Iterate with .items()
dict.items() yields pairs of keys and values. This lets you unpack both at once inside a loop. If you only need the labels, use .keys(). If you only care about the contents, use .values().

.get(): safe lookup with a default

inventory = {'apples': 5}
print(inventory.get('bananas', 0))   # prints 0
# print(inventory['bananas'])        # would raise KeyError
Avoid KeyError by supplying a fallback
When a key might be missing, square brackets crash your program. .get() returns the value if present, or your chosen fallback otherwise.

.update(): merge another dict

config = {'debug': False, 'port': 80}
config.update({'debug': True, 'timeout': 30})
print(config)
Bulk update in one call
update() takes another dictionary and merges it into the current one. Existing keys are overwritten; new ones are added.

Counting occurrences

words = ['cat', 'dog', 'cat']
counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1
print(counts)
Build a frequency dict by hand
This pattern is the foundation of frequency analysis. For each item, you check if it exists (defaulting to zero), then increment its count.

Deleting keys

d = {'a': 1, 'b': 2}
del d['a']          # removes key 'a'
removed = d.pop('b')# returns value and deletes
print(removed)
del vs .pop()
del is a statement that removes the entry. .pop() is a method that both retrieves the value and deletes it, making it useful when you need to use the data before it disappears.

Your turn

0 of 3 solved

Exercise 1

+30 XP
Write a function get_value(d, key, fallback=None) that safely retrieves the value for key from dictionary d. If the key is missing or its value is an empty string, return fallback. Use .get() to avoid raising KeyError.
def get_value(d, key, fallback=None):
    return 'not written yet'

Run your code to check it against the tests.

Exercise 2

+30 XP
Write a function merge_and_trim(base, extra) that returns a new dict equal to base updated with every entry from extra, but then removes any key whose value is the empty string. Do not mutate either input.
def merge_and_trim(base, extra):
    pass

Run your code to check it against the tests.

Exercise 3

+30 XP
Write a function count_tags(log) for server request logs. Each line looks like 'GET /api/users tag:auth tag:user'. Split every line on whitespace and, for each token that starts with 'tag:', split it on the colon and keep the part after it and add one to that tag's running total in a dictionary. Use .get() to read the running total so a tag you have not seen starts at zero. Return the dictionary. Use plain loops -- no comprehensions.
def count_tags(log):
    pass

Run your code to check it against the tests.