Search code examples
pythonsqlitebottle

Recommended method for grouping sqlite.Row rows


Given the following list (from an sqlite query):

[('job1', 'location1', 10), 
('job1', 'location2', 10),
('job2', 'location1', 5),
('job3', 'location1', 10),
('job3', 'location3', 10)]

I'd like to have the following rendered in my tpl template:

job1
location1: 10
location2: 10

job2
location1: 5

job3
location1: 10
location3: 10

I can probably get this done with setdefault

d = {}

for job in jobs:
    d.setdefault(job[0], {}).update({job[1]: job[2]})

but I'm wondering what is the standard or best practice way of doing this?

Cheers,


Solution

  • Here's how I'd make your code more 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)
    

    What I changed:

    1. Use a defaultdict.
    2. Use tuple unpacking for additional readability.