首页 > 解决方案 > 如何使用列表值创建嵌套字典?

问题描述

我有以下两个查询集:

opus = Work_Music.objects.filter(composerwork__person=self.kwargs['pk'], level=0).order_by('date_completed')
event = LifeEvent.objects.filter(person=self.kwargs['pk']).order_by('date_end')

第一个是作曲家的作品,第二个是他的生活事件。

我想创建一个嵌套字典:第一级按年份键入。第二级有两个键“工作”和“生活”。它应该是一个值列表,因为在给定的一年中可能有多个工作和事件。

我写了以下内容:

    # timeline = defaultdict(list)
    timeline = dict()
    for o in opus:
        if o.date_comp_f not in timeline:
            timeline[o.date_comp_f] = {}
            timeline[o.date_comp_f]['work'] = {}
            timeline[o.date_comp_f]['work'].append(o)
        else:
            timeline[o.date_comp_f]['work'].append(o)
    for e in event:
        if e.date_end_y not in timeline:
            timeline[e.date_end_y] = {}
            timeline[e.date_end_y]['life'] = {}
            timeline[e.date_end_y]['life'].append(e)
        else:
            timeline[e.date_end_y]['life'].append(e)
    timeline = dict(timeline)

我还想按时间顺序对第一级键进行排序。我该怎么做呢?我不断收到关键错误。

标签: pythondjangopython-3.xdjango-modelsdjango-queryset

解决方案


{}当您想使用列表时,您正在使用?我猜这是一个错字,但这里是修复(有一些简化):

# timeline = defaultdict(list)
timeline = dict()
for o in opus:
    if o.date_comp_f not in timeline:
        timeline[o.date_comp_f] = {}
        timeline[o.date_comp_f]['work'] = []
    timeline[o.date_comp_f]['work'].append(o)
for e in event:
    if e.date_end_y not in timeline:
        timeline[e.date_end_y] = {}
        timeline[e.date_end_y]['life'] = []
    timeline[e.date_end_y]['life'].append(e)

timeline = dict(timeline)

如果这不起作用,(我认为它不起作用)你能提供Work_MusicLifeEvents模型吗?


推荐阅读