`if key in dict` vs. `try/except` – which is more readable idiom?

Exceptions are not conditionals. The conditional version is clearer. That’s natural: this is straightforward flow control, which is what conditionals are designed for, not exceptions. The exception version is primarily used as an optimization when doing these lookups in a loop: for some algorithms it allows eliminating tests from inner loops. It doesn’t have that … Read more

Surprising results with Python timeit: Counter() vs defaultdict() vs dict()

Yes, this is expected; the Counter() constructor uses Counter.update() which uses self.get() to load initial values rather than rely on __missing__. Moreover, the defaultdict __missing__ factory is handled entirely in C code, especially when using another type like int() that is itself implemented in C. The Counter source is pure Python and as such the … Read more

Can’t pickle defaultdict

In addition to Martijn’s explanation: A module-level function is a function which is defined at module level, that means it is not an instance method of a class, it’s not nested within another function, and it is a “real” function with a name, not a lambda function. So, to pickle your defaultdict, create it with … Read more

Format string unused named arguments [duplicate]

If you are using Python 3.2+, use can use str.format_map(). For bond, bond: from collections import defaultdict ‘{bond}, {james} {bond}’.format_map(defaultdict(str, bond=’bond’)) Result: ‘bond, bond’ For bond, {james} bond: class SafeDict(dict): def __missing__(self, key): return ‘{‘ + key + ‘}’ ‘{bond}, {james} {bond}’.format_map(SafeDict(bond=’bond’)) Result: ‘bond, {james} bond’ In Python 2.6/2.7 For bond, bond: from collections import … Read more

How to convert defaultdict to dict?

You can simply call dict: >>> a defaultdict(<type ‘list’>, {‘1’: [‘b’, ‘a’], ‘3’: [‘b’], ‘2’: [‘a’]}) >>> dict(a) {‘1’: [‘b’, ‘a’], ‘3’: [‘b’], ‘2’: [‘a’]} but remember that a defaultdict is a dict: >>> isinstance(a, dict) True just with slightly different behaviour, in that when you try access a key which is missing — which … Read more

Nested defaultdict of defaultdict

The other answers here tell you how to create a defaultdict which contains “infinitely many” defaultdict, but they fail to address what I think may have been your initial need which was to simply have a two-depth defaultdict. You may have been looking for: defaultdict(lambda: defaultdict(dict)) The reasons why you might prefer this construct are: … Read more