[Chartjs]-Django – update dictionary with missing date values, set to 0

1👍

Like the error says, you can not iterate over a date object, so for start_date in seven_days will not work.

You can however use a for loop here like:

for dt in range(7):
    bookings.setdefault(today+datetime.timedelta(dt), 0)

A dictionary has a .setdefault(..) function that allows you to set a value, given the key does not yet exists in the dicionary. This is thus shorter and more efficient than first checking if the key exists yourself since Python does not have to perform two lookups.

EDIT: Since dictionaries are ordered in insertion order (in the CPython version of that was already the case, but seen as an “implementation detail“). Since , you can thus sort the dictionaries with:

bookings = dict(sorted(bookings.items()))

Prior to , you can use an OrderedDict [Python-doc]:

from collections import OrderedDict

bookings = OrderedDict(sorted(bookings.items()))

Leave a comment