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
- [Answer]-How to read csv file row by row in django?
- [Answer]-Number of SQL queries for a django update
Source:stackexchange.com