【发布时间】:2021-04-08 21:34:56
【问题描述】:
我想打印如下内容,但我不知道如何添加/追加到 python dict 数组。
slots = [{
"court_name": "court 1",
"bookings": [{
"start_time": "8pm"
}]
},
{
"court_name": "court 2",
"bookings": [{
"start_time": "8pm"
},
{
"start_time": "9pm"
}]
}]
我有一堆预订位置,我想使用 for 循环像上面一样呈现它们。当我尝试的方法不起作用时,如何将对象附加/添加到字典中?
slots = {}
prev_court = -1
for booking in instances_sorted:
this_court = booking['location_id']
if this_court == prev_court: # court is the same
slots[len(slots)-1]["slots"].append({
"start_time": booking.start_time,
})
else: # new court
slots.append{
"court_name": booking.location__court_name,
"slots" : [{
"start_time": booking.start_time,
}]
}
prev_court = this_court
我觉得这应该很简单,但是当我搜索类似的答案时找不到任何好东西。感谢您的帮助!
【问题讨论】:
-
您要附加到哪个列表?
-
试图追加到slots dict,然后追加到slots["slots"] 列表中?
-
您拥有的大部分都可以。只是第二次调用append应该是
slots.append({,而不仅仅是slots.append{,close应该是})而不是}。 -
我试了一下(仅供参考,我使用的是 Django),上面写着“'dict' object has no attribute 'append'”
-
请阅读ericlippert.com/2014/03/05/how-to-debug-small-programs。通过阅读错误消息、了解问题所在并诊断可能的原因,您应该能够自己找出此类代码的琐碎问题。如果您遇到困难,您应该提出一个引用complete error message 的特定 问题,解释到目前为止您的调试工作的结果,并准确解释您感到困惑的原因。
标签: python python-3.x django dictionary