Python Forum
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
raising multiple exceptions
#11
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))
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  PiCamera - print exceptions? korenron 2 790 Dec-15-2022, 10:48 PM
Last Post: Larz60+
  SystemError: initialization of integer failed without raising an exception Anldra12 2 4,288 Apr-19-2022, 10:50 AM
Last Post: Anldra12
  Class exceptions DPaul 1 1,257 Mar-11-2022, 09:01 AM
Last Post: Gribouillis
  is this a good way to catch exceptions? korenron 14 4,593 Jul-05-2021, 06:20 PM
Last Post: hussaind
  Raising numbers to power ** GJG 3 2,396 Mar-23-2021, 03:43 PM
Last Post: deanhystad
  Python, exceptions KingKhan248 6 2,941 Nov-15-2020, 06:54 AM
Last Post: buran
  Split string between two different delimiters, with exceptions DreamingInsanity 2 1,977 Aug-24-2020, 08:23 AM
Last Post: DreamingInsanity
  handling 2 exceptions at once Skaperen 2 2,261 Jun-27-2020, 08:55 AM
Last Post: Yoriz
  remove spaces with exceptions catosp 4 2,357 May-29-2020, 09:32 AM
Last Post: catosp
  Looking for advice and Guidance on Exceptions used within Functions paul41 1 2,106 Nov-14-2019, 12:33 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020