Dictionaries

Python 3.12 ยท โœ“ verified by execution on 2026-07-23

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type

python
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
print(tel['jack'])
Output
4098

Dictionary Constructors

The dict() constructor builds dictionaries directly from sequences of key-value pairs:

python
print(dict([('sape', 4139), ('guido', 4127)]))
Output
{'sape': 4139, 'guido': 4127}

Deleting Items

It is also possible to delete a key:value pair with del.

python
tel = {'jack': 4098, 'sape': 4139}
del tel['sape']
print(list(tel))
Output
['jack']

Missing Keys

It is an error to extract a value using a non-existent key.

python
tel = {'jack': 4098}
try:
    print(tel['guido'])
except KeyError as e:
    print(repr(e))
Output
KeyError('guido')

To prevent this error, you can use the .get() method.

python
tel = {'jack': 4098}
print(tel.get('guido', 'Not Found'))
Output
Not Found

Dictionary Iteration

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

python ยท visualize
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
    print(k, v)

Check yourself

Lists can be used as keys in a dictionary.

Reveal answer

Lists are mutable and therefore cannot be used as dictionary keys. Attempting to do so raises a TypeError. โ€” Lists are mutable and therefore cannot be used as dictionary keys. Attempting to do so raises a TypeError.

Iterating over a dictionary directly with 'for item in my_dict' returns the values.

Reveal answer

Iterating over a dictionary directly yields its keys, not its values. โ€” Iterating over a dictionary directly yields its keys, not its values.

Dictionaries in Python 3.12 are unordered.

Reveal answer

Since Python 3.7, dictionaries formally preserve the insertion order of their keys. โ€” Since Python 3.7, dictionaries formally preserve the insertion order of their keys.

Challenges

Challenge 1 +15 XP

Write a function count_words(words) that takes a list of strings and returns a dictionary where keys are words and values are the number of times they appear.

python
  • Test 1 โ€” expects "{'apple': 2, 'banana': 1} \n"
Need a hint? (โˆ’25% XP)

Use .get(word, 0) to fetch the current count or 0 if it doesn't exist, then add 1.

Show solution (0 XP)
def count_words(words):
    counts = {}
    for word in words:
        counts[word] = counts.get(word, 0) + 1
    return counts
print(count_words(['apple', 'banana', 'apple']))

Challenge 2 +15 XP

Write a function merge_profiles(p1, p2) that takes two dictionaries and returns a new dictionary combining both. If keys overlap, p2 should win.

python
  • Test 1 โ€” expects "{'name': 'jack', 'age': 40} \n"
Need a hint? (โˆ’25% XP)

Copy the first dictionary, then .update() it with the second.

Show solution (0 XP)
def merge_profiles(p1, p2):
    merged = p1.copy()
    merged.update(p2)
    return merged
print(merge_profiles({'name': 'jack'}, {'age': 40}))