In this post, I show a small fix to an issue that I encountered while building a Django-based application.
I'm quite a fan of the Python standard library, which has many useful gems that ease the development of application.
One of these are defaultdicts, which act like a regular dict, but instead of throwing errors on missing keys, they allow you to set a default value.
This can help simplify code, for example: Sometimes I take a set of models out of the database, and want to group them by one of their attributes in Python. I won't do this in SQL, as I need each single object, not an aggregated result.
Without a defaultdict, you'd have to check during iteration if the dict already has a list for the given key, and if not set it.
While the approach using
setdefault has the least amount of lines, I personally find it quite ugly and never used it in projects.
When you try to iterate such a defaultdict in a Django template, nothing will be rendered in the page at all.
Even if you explicitly use the
dict.items() method, nothing happens:
The reason for this is described in a quite old bug ticket from 2011, which led to a documentation change, which unfortunately is no longer part of the current documentation.
To fix this issue, just cast your variable back to a regular dict before passing it to the template engine: