Python Forum
raising multiple exceptions - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: raising multiple exceptions (/thread-2455.html)

Pages: 1 2


RE: raising multiple exceptions - wavic - Mar-19-2017

The dict is empty when is initialized. 
So when you set a value for a key which doesn't exist within the dict yet, the key is created instantly and it's value is set to an empty list. 
And you append an error message as its first element.

In [1]: from collections import defaultdict

In [2]: from pprint import pprint

In [3]: d = defaultdict(list)

In [4]: for num in range(1, 6):
   ...:     d[num].append((num, num*2))
   ...:     d[num].append((num, num**2))
   ...:     

In [5]: pprint(d)
defaultdict(<class 'list'>,
            {1: [(1, 2), (1, 1)],
             2: [(2, 4), (2, 4)],
             3: [(3, 6), (3, 9)],
             4: [(4, 8), (4, 16)],
             5: [(5, 10), (5, 25)]})
The above is equal to:

d = {}
for num in range(1, 6):
    if not num in d:
        d[num] = []
        d[num].append((num, num*2))
        d[num].append((num, num**2))