在以datetime为键的字典中使用iteritems

2024-09-28 01:27:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典update_fields,它有键/值对,其中值是另一个字典:

{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}}

我想根据每个键值创建另一个字典(或者以某种方式提取它),但是当我尝试以下操作时:

^{pr2}$

我得到AttributeError: 'datetime.date' object has no attribute 'iteritems'

当我这样做的时候:

^{3}$

我得到TypeError: 'datetime.date' object is not iterable

我会做错什么?它可能与外部字典键是datetime有关吗?无论我做什么尝试,我似乎都无法突破这个键并访问它的值。在


Tags: datetimedate字典t1000t1430t0645t1645t0600
3条回答

在Python中迭代字典时,默认情况下,迭代键。如果要迭代值,请尝试update_fields.values()update_fields.itervalues()

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

如果你想迭代项目,你应该使用update_fields.items()或{}

^{pr2}$

update_date.iteritems()更改为update_fields[update_date].iteritems()

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

这是因为你试图在键上迭代。在

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

相关问题 更多 >

    热门问题