如何从Python字典生成预订用HTML表格?
解决方案
首先,我们先明确结构化数据的核心需求:你的booked_view需要包含三个关键部分——时段列表(表格列标题)、日期列表(表格行标题)、二维状态矩阵(行对应日期,列对应时段,值为True/False标记预订状态)。以下是完整的实现步骤:
步骤1:将原始字典整理为结构化的booked_view
假设你的原始字典结构如下(可替换为实际数据):
from datetime import datetime # 示例原始预订字典 bookings = { datetime(2024, 5, 20): [ {"slot_id": "9:00", "booked": True}, {"slot_id": "10:00", "booked": False}, {"slot_id": "11:00", "booked": True} ], datetime(2024, 5, 21): [ {"slot_id": "9:00", "booked": False}, {"slot_id": "10:00", "booked": True}, {"slot_id": "11:00", "booked": False} ] }
执行以下代码整理数据:
# 提取所有唯一时段并按顺序排序 slots = sorted({slot["slot_id"] for date_data in bookings.values() for slot in date_data}) # 提取日期并格式化为YYYY-MM-DD字符串,同时按日期排序 sorted_dates = sorted(bookings.keys()) dates_str = [date.strftime("%Y-%m-%d") for date in sorted_dates] # 构建预订状态矩阵:行对应日期,列对应时段 status_matrix = [] for date in sorted_dates: # 按时段顺序匹配当前日期的预订状态 sorted_slots = sorted(bookings[date], key=lambda x: x["slot_id"]) status_row = [slot["booked"] for slot in sorted_slots] status_matrix.append(status_row) # 最终的结构化booked_view booked_view = { "slots": slots, "dates": dates_str, "status": status_matrix }
步骤2:嵌套循环生成HTML表格
通过字符串拼接实现表格生成,核心是两层循环遍历日期和时段:
def generate_booking_table(booked_view): # 初始化HTML表格标签,添加基础样式 html = '<table border="1" cellpadding="8" cellspacing="0" style="border-collapse: collapse;">' # 生成表头行:第一列为空,后续为时段标题 html += '<tr><th></th>' for slot in booked_view["slots"]: html += f'<th>{slot}</th>' html += '</tr>' # 生成内容行:每行对应一个日期,第一列为日期,后续为各时段预订状态 for idx, date in enumerate(booked_view["dates"]): html += f'<tr><th>{date}</th>' for is_booked in booked_view["status"][idx]: # 已预订单元格显示"X",否则为空 cell_content = "X" if is_booked else "" # 可选:给已预订单元格添加背景色 cell_style = 'style="background-color: #ffeeee;"' if is_booked else '' html += f'<td {cell_style}>{cell_content}</td>' html += '</tr>' # 闭合表格标签 html += '</table>' return html # 生成并输出HTML result_html = generate_booking_table(booked_view) print(result_html)
效果说明
生成的HTML表格会呈现:
- 第一行是时段标题,首单元格为空
- 每行首列是日期,后续单元格对应该时段的预订状态,已预订的显示
X(可通过cell_style参数添加高亮样式)
内容的提问来源于stack exchange,提问作者mrbanks
相关产品推荐
相关产品推荐

