【问题标题】:How to created a nested dictionary with list values?如何使用列表值创建嵌套字典?
【发布时间】:2020-01-29 06:03:57
【问题描述】:

我有以下两个查询集:

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)

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

【问题讨论】:

  • 能否提供Work_MusicLifeEvents的型号?如果没有看到 FK 关系,这很难想象

标签: python django python-3.x django-models django-queryset


【解决方案1】:

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

# 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 模型?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 2022-11-01
    相关资源
    最近更新 更多