Question: Use iteritems in a dictionary with datetime as key

Question

Use iteritems in a dictionary with datetime as key

Answers 3
Added at 2016-12-01 16:12
Tags
Question

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.

Answers
nr: #1 dodano: 2016-12-01 16:12

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}
nr: #2 dodano: 2016-12-01 16:12

When you are iterating over a dictionary in Python, by default, you iterate over keys. If you want to iterate over values, try update_fields.values() or perhaps update_fields.itervalues()

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

And if you want to iterate over items, you should use update_fields.items() or update_fields.iteritems()

for update_date, values in update_fields.iteritems():
    timeslot_fields = {timeslot: value for (timeslot, value) in values.iteritems()}
nr: #3 dodano: 2016-12-01 16:12

Change update_date.iteritems() to update_fields[update_date].iteritems(),

for update_date in update_fields:
    timeslot_fields = {timeslot: value for (timeslot, value) in update_fields[update_date].iteritems()}
Source Show
◀ Wstecz