Below is typical feedback to a student.

What do others think regarding my discussion of using try /except
in routine dict manipulation?

Kirby


===

Yes perfect.  Good work.

        try:
            res_dict[ext] += 1
        except KeyError:
            res_dict[ext] = 1

This code is not atypical and you'll find some polarization among
Pythonistas about whether this is good style.  Another construct:

       res_dict[ext] = res_dict.get(ext, 0) + 1

is the one I favor.  I think of a "key not found" event
in a dict as "routine, to be expected" whereas I think of
try: / except: as for "crying wolf" (not for everyday
contingencies).  The opposite bias is:  why make that
distinction, try: / except: is a perfectly reasonable
construct for trapping a new key to a dict.

In any case, good Python.

-Kirby
_______________________________________________
Edu-sig mailing list
Edu-sig@python.org
http://mail.python.org/mailman/listinfo/edu-sig

Reply via email to