python - 分组 sqlite.Row 行的推荐方法
问题描述
给定以下列表(来自 sqlite 查询):
[('job1', 'location1', 10),
('job1', 'location2', 10),
('job2', 'location1', 5),
('job3', 'location1', 10),
('job3', 'location3', 10)]
我想在我的 tpl 模板中呈现以下内容:
job1
location1: 10
location2: 10
job2
location1: 5
job3
location1: 10
location3: 10
我可能可以使用 setdefault 完成此操作
d = {}
for job in jobs:
d.setdefault(job[0], {}).update({job[1]: job[2]})
但我想知道这样做的标准或最佳实践方式是什么?
干杯,
解决方案
以下是我如何让你的代码更 Pythonic:
from collections import defaultdict
d = defaultdict(dict)
for (job_id, location, value) in jobs:
d[job_id][location] = value
# if you need an actual dict at the end (and not a defaultdict),
# use d = dict(d)
我改变了什么:
- 使用defaultdict。
- 使用元组解包来增加可读性。
推荐阅读
- sql - 将数据除以会话开始/结束值
- sql-server - 在已 CAST 到 XML 的文本字段上运行 XQuery
- r - 在 R 中通过至少 3 个单独的因素制作比例数据框
- sql - liquibase 中的大型查询执行
- excel - 有没有办法在 excel 上使用聚合函数来带回满足多个标准 excel 的多个结果?
- swift - 如何使用 NSButton 在 NSTouchBar 中模拟按键?
- python - 按逗号拆分列表以及如何从拆分中的引号中排除逗号和引号
- php - 如何从循环中排除帖子特色图片?
- react-native - 反应原生 ui 小猫按钮图标
- javascript - 重定向到 Node.js 中特定用户的信息页面