简体   繁体   English

如何使用列表值创建嵌套字典?

[英]How to created a nested dictionary with list values?

I have the follow two queryset:我有以下两个查询集:

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')

The first pulls the work of a composer and the second pulls his life events.第一个是作曲家的作品,第二个是他的生活事件。

I want to create a nested dictionary: The first level is keyed by year.我想创建一个嵌套字典:第一级按年份键入。 The second level has two keys 'work' and 'life'.第二级有两个键“工作”和“生活”。 It should be a list of values because there could be multiple work and events in a given year.它应该是一个值列表,因为在给定的一年中可能有多个工作和事件。

I have written following:我写了以下内容:

    # 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)

I also want to sort the first level key in chronological order.我还想按时间顺序对第一级键进行排序。 How do I do this?我该怎么做呢? I keep getting Key errors.我不断收到关键错误。

You were using {} when you wanted to use a list?当您想使用列表时,您使用的是{} I'm guessing this was a typo, but here is the fix (with a few simplifications):我猜这是一个错字,但这里是修复(有一些简化):

# 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)

If this doesn't work, (which I assume it doesn't) can you please provide the Work_Music and LifeEvents models?如果这不起作用,(我认为它不起作用)您能否提供Work_MusicLifeEvents模型?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM