How can I use two keys with defaultdict?
<p>I am trying to create a defaultdict with nested keys. Here is the view that I wrote, but apparently multiple keys don't work in defaultdict.</p>

<pre><code>def routine_view(request, klass_id):
    days = Routine.DAYS
    periods = Routine.PERIODS

    class_details = defaultdict(list)
    classes = Routine.objects.filter(klass_id=klass_id)

    for cls in classes:
        class_details[cls.day][cls.period].append(cls)

    context = {
        "days": days,
        "periods": periods,
        "class_details": class_details
    }
    return render(request, "routine/routine_view.html", context)
</code></pre>

<p>When I run this view I get the following error:</p>

<pre><code>IndexError at /routine/1/
list index out of range
</code></pre>

<p>Your question isn't totally clear, but I think you want a defaultdict which itself contains a defaultdict of lists. So:</p>

<pre><code>class_details = defaultdict(lambda: defaultdict(list))
</code></pre>

<p>Alternatively, you may not need a nested dict at all; you could instead use the original defauldict with key that is a tuple:</p>

<pre><code>class_details[(cls.day, cls.period)].append(cls)
</code></pre>

python django defaultdict