推荐的sqlite.Row行分组方法

时间:2019-03-23 19:34:18

标签: python sqlite bottle

给出以下列表(来自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]})

但是我想知道这样做的标准或最佳做法是什么?

干杯

1 个答案:

答案 0 :(得分:1)

这是我要使您的代码更具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)

我更改了:

  1. 使用defaultdict
  2. 使用元组拆包以提高可读性。