I have a list of objects (strings in this example) which I want to categorize according to a certain characteristic returned by a function.
For example, consider the following list:
['sky', 'ocean', 'grass', 'tomato', 'leaf']
and a function color(item)
which returns the color of the string passed to it, e.g. color('sky')
returns 'blue'
. I now want to transform the list into a dictionary or a list of lists which groups the items according to their color/the value returned by the function. A possible result would look like this:
{
'blue': ['sky', 'ocean'],
'green': ['grass', 'leaf'],
'red': ['tomato']
}
I do not care for the key itself, only that the items are grouped accordingly, so nested lists would be fine too. Just trying to do this in a pythonic way :)
I think I'd go about this question this way:
from collections import defaultdict
D = defaultdict(list)
a = ['sky', 'ocean', 'grass', 'tomato', 'leaf']
for item in a:
D[color(item)].append(item)
That gives you a dictionary of lists, keyed by colors, that contains items for that category.