`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

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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)