如何根据对象的属性创建字典?

时间:2015-05-08 20:08:19

标签: python django python-2.7 django-templates django-views

我有一个名为log_entries的词典:

log_entries = {datetime.date(2015, 5, 2): {'before_bedtime': '',
  'before_breakfast': '',
  'before_dinner': '',
  'before_lunch': ''},
 datetime.date(2015, 5, 3): {'before_bedtime': '',
  'before_breakfast': '',
  'before_dinner': '',
  'before_lunch': ''},
 datetime.date(2015, 5, 4): {'before_bedtime': '',
  'before_breakfast': '',
  'before_dinner': '',
  'before_lunch': ''},
 datetime.date(2015, 5, 5): {'before_bedtime': '',
  'before_breakfast': '',
  'before_dinner': '',
  'before_lunch': ''},
 datetime.date(2015, 5, 6): {'before_bedtime': '',
  'before_breakfast': '',
  'before_dinner': '',
  'before_lunch': ''},
 datetime.date(2015, 5, 7): {'before_bedtime': '',
  'before_breakfast': '',
  'before_dinner': '',
  'before_lunch': ''},
 datetime.date(2015, 5, 8): {'before_bedtime': '',
  'before_breakfast': '',
  'before_dinner': '',
  'before_lunch': ''}}

我有一个名为bg_readings的可迭代对象,每个阅读都有一个日期时间属性,一个用餐属性(字符串......或者' before_breakfast',' before_lunch',&#39 ; before_dinner'或' before_bedtime'),以及读取属性(int)。

对于log_entries中的给定日期,我想使用bg_reading的bg_reading读取值填充嵌套字典的before_<meal>值,并且日期相同。

我已经尝试了下面的代码,但结果是一个log_entries字典,其中每个值都来自bg_readings iterable中的最后一个bg_reading。

for key in log_entries:
    for reading in bg_readings:
        if reading.logDatetime.date() == key:
            log_entries[key][reading.meal] = reading.reading

以上代码的结果(字典中每个日期键的数据仅来自bg_readings可迭代中的最后一个对象,而不是来自具有匹配日期的bg_reading ):

{datetime.date(2015, 5, 2): {'before_bedtime': 119,
  'before_breakfast': 99,
  'before_dinner': 115,
  'before_lunch': 111},
 datetime.date(2015, 5, 3): {'before_bedtime': 119,
  'before_breakfast': 99,
  'before_dinner': 115,
  'before_lunch': 111},
 datetime.date(2015, 5, 4): {'before_bedtime': 119,
  'before_breakfast': 99,
  'before_dinner': 115,
  'before_lunch': 111},
 datetime.date(2015, 5, 5): {'before_bedtime': 119,
  'before_breakfast': 99,
  'before_dinner': 115,
  'before_lunch': 111},
 datetime.date(2015, 5, 6): {'before_bedtime': 119,
  'before_breakfast': 99,
  'before_dinner': 115,
  'before_lunch': 111},
 datetime.date(2015, 5, 7): {'before_bedtime': 119,
  'before_breakfast': 99,
  'before_dinner': 115,
  'before_lunch': 111},
 datetime.date(2015, 5, 8): {'before_bedtime': 119,
  'before_breakfast': 99,
  'before_dinner': 115,
  'before_lunch': 111}}

如何使用相应的bg_reading值正确填充此字典?

我最终希望将生成的字典传递给Django模板,并按日期和用餐显示bg_readings表,因此我对使用视图逻辑,模板标记或两者的解决方案感到满意。 / p>

0 个答案:

没有答案