Using defaultdict to replace try and/or if statements in python

Viewed 1097

I have recently found and started using default dictionaries to replace several more bulky constructs. I have read in 'the zen of python' that one of the key points of python is "There should be one-- and preferably only one --obvious way to do it."

Based on that criteria (or perhaps more practically based on memory usage, or speed) which of the following (or something totally different) would be best? I have a hunch that the first is correct, but would like other people's opinions.

my_dict = defaultdict(int)
for generic in iterable:
    my_dict[generic] +=1

or:

my_dict = {}
for generic in iterable:
    if generic not in my_dict:
        my_dict[generic] = 1
    else:
        my_dict[generic]+=1

or:

my_dict = {}
for generic in iterable:
    try:
        my_dict[generic] += 1
    except(KeyError):
        my_dict[generic] = 1

Same can be said of using my_dict = defaultdict(list) and using append functions. Assume that multiple for loops, or other conditionals are used rather than simply counting generic values from a single iterable as that would obviously have different features.

2 Answers
Related