add an element to a dict if it does not exist or increment it by 1 if it does.
Use the get() method to return the current value or 0 if the key does not exist, then add 1 and assign it back to the key1:
d[key] = d.get(key, 0) + 1
Use the setdefault() method to set the default value to 0 if the key does not exist, then add 1 and assign it back to the key2:
d[key] = d.setdefault(key, 0) + 1
Use the defaultdict class from the collections module to create a dict that automatically assigns 0 to a missing key, then add 1 and assign it back to the key3:
from collections import defaultdict
d = defaultdict(int)
d[key] += 1