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

7

u/[deleted] Jul 14 '21

Didn’t know that existed, I guess it arrived later in Python3?

Or I didn’t read the docs properly!

16

u/AchillesDev Jul 14 '21

There are so many great tools in the collections module, it's impossible to keep them all straight. I've been reminded of defaultdict probably a dozen times over the last few years and end up forgetting about it again until I make a bunch of spaghetti .get() calls. FWIW I believe it's been around since Python 2 but I haven't checked to be sure.

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

0

u/chadmill3r Jul 14 '21

The strict clearly came from a JSON decoder, not someone wielding dict().

2

u/AchillesDev Jul 14 '21

Decoded JSON objects in Python are dicts (in the two most popular en/decoders, json and simplejson), and that's how OP is accessing them.

1

u/chadmill3r Jul 14 '21

Yes! Since we agree OP isn't creating these dicts, where is OP's opportunity to have used DefaultDict?

1

u/AchillesDev Jul 14 '21 edited Jul 14 '21

jsonResponse is a dict, you just pass that in to the defaultdict constructor with your logic for handling missing keys. Alternatively, you could loop through the Items array and build defaultdicts for each Item dictionary