voodoo-burger voodoo-burger - 7 days ago 5
Python Question

Use iteritems in a dictionary with datetime as key

I have a dictionary

update_fields
that has key/value pairs where the value is another dictionary:

{datetime.date(2016, 12, 2): {'t1030': 0, 't1045': 0, 't0645': 0, 't1645': 0, 't0600': 0, 't1415': 0, 't1000': 0, 't1430': 0, 't0700': 0, 't1800': 0, 't1715': 0, 't1630': 0, 't1615': 0, 't1945': 0, 't1730': 0, 't1530': 0, 't1515': 0, 't0830': 0, 't0915': 0, 't1245': 0, 't1300': 0, 't1600': 0, 't1900': 0, 't2000': 0, 't2115': 0, 't0715': 0}, datetime.date(2016, 12, 1): {'t1030': 0, 't1045': 0, 't0645': 0, 't1645': 0, 't0600': 0, 't1415': 0, 't1000': 0, 't1430': 0, 't0700': 0, 't1800': 0, 't1715': 0, 't1630': 0, 't1615': 0, 't1945': 0, 't1730': 0, 't1530': 0, 't1515': 0, 't0830': 0, 't0915': 0, 't1245': 0, 't1300': 0, 't1600': 0, 't1900': 0, 't2000': 0, 't2115': 0, 't0715': 0}}


I want to create another dictionary from each key value (or somehow extract it as-is), but when I try this:

for update_date in update_fields:
timeslot_fields = {timeslot: value for (timeslot, value) in update_date.iteritems()}


I get
AttributeError: 'datetime.date' object has no attribute 'iteritems'


And when I try it like this:

for update_date, values in update_fields:
timeslot_fields = {timeslot: value for (timeslot, value) in values.iteritems()}


I get
TypeError: 'datetime.date' object is not iterable


What could I be doing wrong? Could it have something to do with the fact that the outer dictionary key is a datetime? No matter what I try I can't seem to break out of the key and access its value.

Answer

It's because you are trying to iterate on the key.

for update_date in update_fields:
    items = update_fields[update_date].items()
    timeslot_fields = {timeslot: value for (timeslot, value) in items}