在 defaultdict 中追加到字典

Append to dictionary in defaultdict

我有一个 defaultdict,我想创建一个字典作为值部分,我可以附加到这个字典吗?目前我正在附加到一个列表,这意味着字典是分开的。

dates = [datetime.date(2016, 10, 17), datetime.date(2016, 10, 18), datetime.date(2016, 10, 19), datetime.date(2016, 10, 20), datetime.date(2016, 10, 21), datetime.date(2016, 10, 22), datetime.date(2016, 10, 23)]

e = defaultdict(list)
for key, value in d.iteritems():
    value = (sorted(value, key=itemgetter('date'), reverse=False))
    for date in dates:
        for i in value:
            if i['date'] == str(date) and i['time'] == 'morning':
                value1 = float(i['value1'])
                temp = {'val_morning': value1 }
                e[str(date)].append(temp)
            elif ii['date'] == str(date) and i['time'] == 'evening':
                value2 = float(i['value2'])
                temp = {'val_evening': value2 }
                e[str(date)].append(temp)

这导致:

{'2016-10-20': [{'val_morning': 0.0}, {'val_evening': 0.0}], '2016-10-21': [{'val_morning': 0.0}, {'val_evening': 0.0}]}

编辑 期望的输出:

{                        
    '2016-10-20': {'val_morning': 0.0, 'val_evening': 0.0}, 
    '2016-10-21': {'val_morning': 0.0, 'val_evening': 0.0}
}

如果我没理解错的话,你想用字典替换列表,稍后你可以向其中添加值。

如果是这样你可以这样做:

dates = [datetime.date(2016, 10, 17), datetime.date(2016, 10, 18), datetime.date(2016, 10, 19), datetime.date(2016, 10, 20), datetime.date(2016, 10, 21), datetime.date(2016, 10, 22), datetime.date(2016, 10, 23)]

e = defaultdict(dict)
for key, value in d.iteritems():
    value = (sorted(value, key=itemgetter('date'), reverse=False))
    for date in dates:
        for i in value:
            if i['date'] == str(date) and i['time'] == 'morning':
                value1 = float(i['value1'])
                temp = {'val_morning': value1 }
                e[str(date)].update(temp) #### HERE i replaced append with update!
            elif ii['date'] == str(date) and i['time'] == 'evening':
                value2 = float(i['value2'])
                temp = {'val_evening': value2 }
                e[str(date)].update(temp)#### HERE i replaced append with update!

我只是用 update 替换了追加(当然还让 defaultdict 使用 dict 而不是 list)

如果我没理解错的话

import datetime
dates = [datetime.date(2016, 10, 17), datetime.date(2016, 10, 18), datetime.date(2016, 10, 19), datetime.date(2016, 10, 20), datetime.date(2016, 10, 21), datetime.date(2016, 10, 22), datetime.date(2016, 10, 23)]

dict_x = {}
for i in map(str,set(dates)):
    dict_x[i] = {'val_morning': 0.0, 'val_evening': 0.0}

dict_x

output :
{'2016-10-17': {'val_evening': 0.0, 'val_morning': 0.0},
 '2016-10-18': {'val_evening': 0.0, 'val_morning': 0.0},
 '2016-10-19': {'val_evening': 0.0, 'val_morning': 0.0},
 '2016-10-20': {'val_evening': 0.0, 'val_morning': 0.0},
 '2016-10-21': {'val_evening': 0.0, 'val_morning': 0.0},
 '2016-10-22': {'val_evening': 0.0, 'val_morning': 0.0},
 '2016-10-23': {'val_evening': 0.0, 'val_morning': 0.0}}