I find myself repeating the following code (or something similar) often:
users = {}
for d in data:
if d['user'] in users.keys():
users[d['user']].append(d)
else:
users[d['user']] = [d]
Here, data is a list of dicts, and I want to split the list into smaller lists mapped to their d["user"] value as a key in a dictionary.
I would like a way of doing this in a single line, because these multiple lines annoy me.
The only way I can think of doing this, however, involve changing my O(N) algorithm (above) into an O(N^2) algorithm, like:
users = {d["user"]: [d for d in data if d["user"] == u] for d in data}
Obviously, this inefficiency is unacceptable...
You can use this kind of syntax for tests
wich fits the kind of needs you have, especially dealing with comprehension lists and all. For your purpose, this should do :