Nealon Nealon - 10 days ago 6
Python Question

Create Sublists Based on Property in Python

I've got a list of toys, and each of those toys has a color associated with it. Each toy is unique, but some of them may have the same color. I want to group all of the toys by their color and put them into sublists. So essentially, I want a list of all the toys grouped by color.

I've seen a few posts on how to do this with a Boolean or a finite number of values, but I want to be able to do it with any color, or rather, any string.

Answer

Try this:

from collections import defaultdict

toys_color = defaultdict(list)
for toy in toys:
    toys_color[toy.color].append(toy)
list_toys_color = list(toys_color.items())

If you don't want the color with each group, use this line instead:

list_toys_color = list(toys_color.values())