You can't write this as a comprehension: each element of the comprehension is a filtered version of the things you are iterating over. All elements in the comprehension are processed and appended to a single container independently. You are asking to append to different containers depending on the key, so no comprehension.
The simplest approach I can think of instead is to use collections.defaultdict
:
from collections import defaultdict
result = defaultdict(list)
for item, data in myDict.items():
result[data['attr']].append(item)
Now you could cheat the system by creating a function that has some unrelated side-effects and use that to filter the output. In that case, the only real benefit would be to write the already legible for
loop in one line. You would want to consume the comprehension without actually storing the results of the function:
from collections import deque, defaultdict
results = defaultdict(list)
deque((results[data['attr']].append(item) for item, data in myDict.items()), maxlen=0)
This trick using collections.deque
with maxlen=0
is one of the faster ways to consume an iterator purely for its side-effects.