python - 如何附加到 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
我觉得这应该很简单,但是当我搜索类似的答案时找不到任何好东西。谢谢您的帮助!
解决方案
我遇到的问题是我将插槽声明为字典,而实际上它是一个列表。所以解决方案看起来像这样。
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
推荐阅读
- memory-leaks - 英特尔 MKL SPBLAS 的内存泄漏
- android - 如何比较我选择的日历结束时间是否早于 12 小时日历时间的所选日历开始时间?
- twig - Twig:如何获取视图机器名称、标签等
- java - 我在类路径中设置了我的 servlet-api.jar,但是当我导入 javax.servlet.http.*; 它给出了这个包不存在的编译错误,为什么?
- java - 如何在java中将密钥对导入密钥库并使密钥不可导出
- python - python elementTree XML解析器的性能问题
- vue.js - 布局文件中 Nuxt.js 的元属性在中间件中不起作用
- prestashop-1.6 - 如何将自定义 id 添加到表单字段 prestaShop 表单助手
- python - 如何将 for 循环中的字典附加到列表中(具体示例)
- c++ - 多次调用存储过程时,mySQL C++ 连接器“命令不同步”