[Answer]-Queryset to dict with common fields as keys

1๐Ÿ‘

โœ…

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']})
๐Ÿ‘คMark Tolonen

0๐Ÿ‘

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)
๐Ÿ‘คlwb

Leave a comment