Bayard Randel
Bayard Randel

Reputation: 10086

queryset to dict with common fields as keys

Given a queryset like this:

[<'item', 'category1'>, <'item2', 'category1'>, <'item3', 'category2'>]

What is the Pythonic way to 'zip' this to a dict where the common categories are the keys, with values as lists? e.g.

{ category1: [item, item2], category2: [item3] }

Upvotes: 0

Views: 114

Answers (2)

lwb
lwb

Reputation: 1

I'm sure their is a cleaner approach, but the following should certainly work:

qs = [('item', 'category1'), ('item2', 'category1'), ('item3', 'category2')]
for item, cat in qs:
if cat not in cat_dict:
    cat_dict[cat] = []
cat_dict[cat].append(item)

Upvotes: 0

Mark Tolonen
Mark Tolonen

Reputation: 177406

Use a defaultdict. If a key does not exist in a dictionary it returns a default-constructed item. Below it returns an empty list, so each item can be appended without special handling for a non-existing key.

from collections import defaultdict
D = defaultdict(list)
data = [('item', 'category1'), ('item2', 'category1'), ('item3', 'category2')]

for item,category in data:
    D[category].append(item)
print(D)

Output:

defaultdict(<class 'list'>, {'category2': ['item3'], 'category1': ['item', 'item2']})

Upvotes: 1

Related Questions