首先,从这样的字典列表中提取唯一的日期,
event_types = ['NO', 'CL', 'PV', 'TT']
dict_list = [{'event_date__count': 5,
'event_type': 'NO',
'event_week': datetime.date(2018, 11, 5)},
{'event_date__count': 2,
'event_type': 'NO',
'event_week': datetime.date(2018, 11, 12)},
{'event_date__count': 2,
'event_type': 'CL',
'event_week': datetime.date(2018, 11, 12)},
{'event_date__count': 2,
'event_type': 'PV',
'event_week': datetime.date(2018, 11, 12)}]
dates = []
for item in dict_list:
dates.append(item['event_week'])
dates = list(set(dates))
print(dates)
输出:
[datetime.date(2018, 11, 5), datetime.date(2018, 11, 12)]
event_types
对于每个事件,从
dates
列出并检查每个日期的组合
event_type
和
date
若它不存在,则将其附加到字典列表中,否则忽略它。这样做,,
for type in event_types:
found = False
for date in dates:
for item in dict_list:
if item['event_type'] == type and item['event_week'] == date:
found = True
if (found == False):
dict_list.append({'event_date__count': 0,
'event_type': type,
'event_week': date})
dict_list
输出:
[{'event_date__count': 5,
'event_type': 'NO',
'event_week': datetime.date(2018, 11, 5)},
{'event_date__count': 2,
'event_type': 'NO',
'event_week': datetime.date(2018, 11, 12)},
{'event_date__count': 2,
'event_type': 'CL',
'event_week': datetime.date(2018, 11, 12)},
{'event_date__count': 2,
'event_type': 'PV',
'event_week': datetime.date(2018, 11, 12)},
{'event_date__count': 0,
'event_type': 'CL',
'event_week': datetime.date(2018, 11, 5)},
{'event_date__count': 0,
'event_type': 'PV',
'event_week': datetime.date(2018, 11, 5)},
{'event_date__count': 0,
'event_type': 'TT',
'event_week': datetime.date(2018, 11, 5)},
{'event_date__count': 0,
'event_type': 'TT',
'event_week': datetime.date(2018, 11, 12)}]