首页 > 解决方案 > 如何附加到 python subdict 数组?

问题描述

我想打印如下内容,但我不知道如何添加/追加到 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

我觉得这应该很简单,但是当我搜索类似的答案时找不到任何好东西。谢谢您的帮助!

标签: pythonpython-3.xdjangodictionary

解决方案


我遇到的问题是我将插槽声明为字典,而实际上它是一个列表。所以解决方案看起来像这样。

slots = []
prev_court = -1
N = 0
for booking in instances_sorted:
    this_court = booking['location_id']
    if this_court == prev_court: # court is the same
        N = N + 1
        slots[N]["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

推荐阅读