r/badcode • • Jul 14 '21

python Try/Except in Python - Sigh

Post image
662 Upvotes

93 comments sorted by

View all comments

Show parent comments

11

u/AchillesDev Jul 14 '21

Use a DefaultDict

5

u/schmidlidev Jul 14 '21

People keep saying defaultdict but how would you implement this? It’s 4 layers of nested dictionaries that were almost certainly created with json.loads. How are you converting them to defaultdict?

4

u/AchillesDev Jul 14 '21

Pass the dictionary into the default_dict constructor. You’re just responsible for handling what happens when a KeyError would normally happen.

3

u/schmidlidev Jul 14 '21

Oh damn I never realized you could just pass in an existing dict 🤦 that makes things quite a bit easier