通过for循环构建dict而无需重复

时间:2019-06-22 06:49:03

标签: python django

我的代码目前在soup.select("table.rightLinks tr.even, table.rightLinks tr.odd") grouped_events.setdefault('VAR', []).append(event)上非常重复。您看到任何更好的编写方式吗?

目前,我最好的主意是在上面插入诸如“归档”等字符串的地方编写一个函数。

event_data_by_organizer[organizer.pk]['events_draft'] = grouped_events.get('VAR')

1 个答案:

答案 0 :(得分:1)

您可以使用defaultdict代替手动调用setdefault。 辅助映射(EVENT_MAPPING)可用于减少用于event_data_by_organizer分配的代码。

由于要对事件进行分组,因此很难进一步缩短group_events(events)(或者至少我看不到方法)。

from collections import defaultdict


EVENT_MAPPING = {
    "archived": "events_archived",
    "draft": "events_draft",
    "past": "events_past",
    "live": "events_live",
}


def group_events(events):
    grouped_events = defaultdict(list)

    for event in events:
        if event.status == EventStatus.ARCHIVED:
            events = grouped_events["archived"]
        elif event.status == EventStatus.DRAFT:
            events = grouped_events["draft"]
        elif event.is_over:
            events = grouped_events["past"]
        else:
            events = grouped_events["live"]

        events.append(event)

    return grouped_events


def set_organizer_events(events_by_organizer, organizer_pk, grouped_events):
    for event, state in EVENT_MAPPING.items():
        events_by_organizer[organizer_pk][state] = grouped_events[event]


my_grouped_events = group_events(my_events)
set_organizer_events(my_organizers, 1, my_grouped_events)