我有一个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}
}
答案 0 :(得分:0)
如果我理解正确,你想用dict替换列表,以后可以添加它的值。
如果是这样,你可以这样做:
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)
答案 1 :(得分:0)
如果我理解正确
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}}