Take the 2-minute tour ×

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 :)

share|improve this question

3 Answers 3

up vote 5 down vote accepted

I think I'd go about this question this way:

from collections import defaultdict

D = defaultdict(list)


for item in a:

That gives you a dictionary of lists, keyed by colors, that contains items for that category.

share|improve this answer
exactly what I was looking for, thanks –  WakiMiko Apr 28 '11 at 16:29

sa = {}
for x in a:
  key = color(x)
  if key in sa:
    sa[key] = [x]

Not sure how pythonic that is, but it's pretty clear. In late enough versions of Python, you can use a default dictionary to make the loop's core cleaner.

share|improve this answer

Slightly modifying the solution 'unwind' has proposed:


def color(x):
    # dummy hash function for demo
    return len(x)

color_map = {}

for x in a:
    key = color(x)

print color_map

The above code example prints:

{3: ['sky'], 4: ['leaf'], 5: ['ocean', 'grass'], 6: ['tomato']}
share|improve this answer

Your Answer


