python - 如何使用列表值创建嵌套字典?
问题描述
我有以下两个查询集:
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)
我还想按时间顺序对第一级键进行排序。我该怎么做呢?我不断收到关键错误。
解决方案
{}
当您想使用列表时,您正在使用?我猜这是一个错字,但这里是修复(有一些简化):
# 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_Music
和LifeEvents
模型吗?
推荐阅读
- python - 如何打开 Python 3.8 IDLE?
- python - 为什么我的 csv 文件用“\t”而不是逗号(“,”)分隔?
- machine-learning - 字符串索引器,CountVectorizer Pyspark 单行
- node.js - sudo npm install -g cordova ionic - 不工作,因为 EEXIST
- c# - User.Identity.GetUserId() 在 .net Core 中总是返回 null
- azure - 部署到 Azure 应用服务时站点不显示
- python - 弹跳球游戏 tkinter 帆布
- python-3.x - 是否可以在 Python3 中使变量成为对类属性的引用?
- swift - swift 5 data.withUnsafeBytes
- python - 尝试使用 matplotlib 为数据框列表制作子图时出现值错误?