jhenninger
jhenninger

Reputation: 707

grouping list of objects according to a certain characteristic

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

Upvotes: 0

Views: 914

Answers (3)

sateesh
sateesh

Reputation: 28673

Slightly modifying the solution 'unwind' has proposed:

a = ['sky', 'ocean', 'grass', 'tomato', 'leaf']

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

color_map = {}

for x in a:
    key = color(x)
    color_map.setdefault(key,[]).append(x)

print color_map

The above code example prints:

{3: ['sky'], 4: ['leaf'], 5: ['ocean', 'grass'], 6: ['tomato']}

Upvotes: 0

g.d.d.c
g.d.d.c

Reputation: 47988

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.

Upvotes: 5

unwind
unwind

Reputation: 399813

a = ['sky', 'ocean', 'grass', 'tomato', 'leaf']

sa = {}
for x in a:
  key = color(x)
  if key in sa:
    sa[key].append(x)
  else:
    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.

Upvotes: 0

Related Questions