Python – DefaultDict Object. Or how to avoid the Key Error.

Have you seen the error below?

Traceback (most recent call last):
  File "C:/Users/foo/PycharmProjects/pythonProject3/main.py", line 29, in <module>
    main()
  File "C:/Users/foo/PycharmProjects/pythonProject3/main.py", line 19, in main
    a['foo'] += 5
KeyError: 'foo'

Of course you have. And you know, that it is because you have written something extremely unwise like this:

    a = dict()
    a['foo'] += 5

Yeah. You cannot increment the value of a non-existent key. Unless…

Sun, football and basketball. In this order.

Unless you do not decide to use the default dictionary object – https://docs.python.org/3/library/collections.html?highlight=defaultdict#collections.defaultdict

Then you can nicely increment anything, without caring whether it exists. And instead of having a key error on the example above, you will have a simple 5. Let’s see the example:

from collections import defaultdict


def main():
    addresses = defaultdict(int)
    addresses['Druzhba 2'] += 100
    addresses['Druzhba 2'] += 100
    addresses['Sofia'] = 20
    addresses['Plovdiv'] +=30
    print_dictionary(addresses)

    football_teams = defaultdict(str)
    football_teams['Bulgaria'] = ['CSKA', 'Levski', 'Lokomotive']
    football_teams['Not Bulgaria'] = 'Manchester United'
    football_teams['Really Not Bulgaria'] += 'PSG'
    print_dictionary(football_teams)

    print(football_teams.__missing__('Bulgaria'))
    print(football_teams.__missing__('Foo'))

def print_dictionary(dict):
    for a, b in dict.items():
        print(f'{a} --> {b}')


if __name__ == '__main__':
    main()

This is what we will get as a result:

That’s all! Enjoy it! 🙂