Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何创建具有列表值的嵌套字典?_Python_Django_Python 3.x_Django Models_Django Queryset - Fatal编程技术网

Python 如何创建具有列表值的嵌套字典?

Python 如何创建具有列表值的嵌套字典?,python,django,python-3.x,django-models,django-queryset,Python,Django,Python 3.x,Django Models,Django 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') 第一个是作曲家的作品,第二个是他的生活事件 我想创建一个嵌套字典:第一个级别按年份设置关键帧。第二

我有以下两个查询集:

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)

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

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


如果这不起作用(我假设它不起作用),你能提供
工作音乐
生活事件
模型吗?

你能提供
工作音乐
生活事件
的模型吗?在没有看到FK关系的情况下,很难将其可视化
# 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)