Many real problems are solved with three dictionary patterns: counting how many times something appears, grouping elements by a criterion and inverting a dictionary.
Pattern 1: counting
To count appearances you use a dictionary that goes from each element to its counter. get(key, 0) avoids the KeyError the first time an element appears:
text = "abracadabra"
count = {}
for letter in text:
count[letter] = count.get(letter, 0) + 1
print(count)
# {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
The same idea works for counting the words of a sentence:
sentence = "the sun and the sea"
count = {}
for word in sentence.split():
count[word] = count.get(word, 0) + 1
print(count) # {'the': 2, 'sun': 1, 'and': 1, 'sea': 1}
Finding the most repeated one
count = {"a": 5, "b": 2, "r": 2}
best = None
for key in count:
if best is None or count[key] > count[best]:
best = key
print(best, count[best]) # a 5
Python also has collections.Counter, which does all this in one line. You will meet it when you learn about modules; for now it is important to know how to do it by hand.
Pattern 2: grouping
To group you use a dictionary whose values are lists. If the key does not exist yet, you first create its empty list:
words = ["sun", "sea", "sky", "moon", "star"]
groups = {}
for word in words:
n = len(word)
if n not in groups:
groups[n] = []
groups[n].append(word)
print(groups)
# {3: ['sun', 'sea', 'sky'], 4: ['moon', 'star']}
Notice that keys can be numbers, not only text.
setdefault: create if it does not exist
setdefault(key, value) returns the value of the key and, if it did not exist, creates it with the value you give. This shortens the previous pattern:
groups = {}
for word in words:
groups.setdefault(len(word), []).append(word)
Pattern 3: inverting a dictionary
Inverting means swapping keys and values, useful to look up in both directions:
es_en = {"hola": "hello", "gato": "cat"}
en_es = {}
for spanish, english in es_en.items():
en_es[english] = spanish
print(en_es) # {'hello': 'hola', 'cat': 'gato'}
It only works well if the values are unique and of an immutable type. If two keys have the same value, the second overwrites the first.
A dictionary as a conversion table
A dictionary replaces a long chain of if/elif when you want to translate one value into another:
names = {"1": "one", "2": "two", "3": "three"}
for digit in "321":
print(names[digit])
# three
# two
# one
Practice in Count words, Letter frequency, Most frequent character, Group by length and Number to text.