【问题标题】:How do I append to python subdict array?如何附加到 python subdict 数组?
【发布时间】: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


【解决方案1】:

update() 方法如果键不在字典中,则将元素添加到字典中。如果键在字典中,它会使用新值更新键。

【讨论】:

  • 感谢您已清除通过了插槽的 else 语句部分,但在 if 语句中出现错误。它说明“KeyError:1”,我有槽[len(slots)-1]["slots"].update({ "start_time": booking.start_time, })
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2022-07-01
    • 2021-10-12
    • 2021-03-21
    • 2018-05-29
    • 2017-07-07
    • 2017-10-17
    • 2017-08-18
    • 2018-07-03
    • 1970-01-01
    相关资源
    最近更新 更多