I'm trying to simplify the following code using list/dict comprehension, in which I want to build a dictionary of lists from a list.
In this example, I take the mod (or any other function) of each item as the key. If the key doesn't exist in the dictionary, a new list is created and the item is appended to the list, otherwise the item is directly appended.
def get_key(val):
return val % 3 # Can be something else, it doesn't matter
dict = {}
data = [i for i in range(10)]
for item in data:
key = get_key(item)
if key in dict:
dict[key].append(item)
else:
dict[key] = [item]
print(dict)
Expected output
{0: [0, 3, 6, 9], 1: [1, 4, 7], 2: [2, 5, 8]}
To simplify the above code, I have tried this ugly approach:
for item in data:
key = get_key(item)
dict[key] = [item] if key not in dict else (dict[key], dict[key].append(item))[0]
However, how to achieve the same thing without the for-loop, using list/dict comprehension as a single expression?
I could think of something like this, but it's not able to append value into a pre-existing list.
{get_key(item):[item] for item in data}
Related posts:
- Create a dictionary with list comprehension
- if/else in a list comprehension (Note: I'm thinking perhaps conditional expressions might work, but not sure how to combine it with the expession)