Three ways to group data

foods = [ ('vegetable', 'cucumber'), ('fruit', 'kiwi'), ('flower', 'Chrysanthemum'), ('vegetable', 'lettuce'), ('nut', 'peanut'), ('seed', 'sunflower seed'), ('fruit', 'avocado'), ('flower', 'Rose'), ('seed', 'rye grain'), ('fruit', 'orange'), ('flower', 'Dahlia'), ('fruit', 'cherry'), ('nut', 'walnut'), ('nut', 'almond'), ('seed', 'sesame'), ('fruit', 'strawberry'), ('seed', 'pumpkin seed'), ('flower', 'Iris'), ] # Variant 1: Using itertools from itertools import groupby func = lambda x: x[0] foods = sorted(foods, key=func) for group, items in groupby(foods, func): print('%s: %s' % (group, [v for _, v in items])) """ flower: ['Chrysanthemum', 'Rose', 'Dahlia', 'Iris'] fruit: ['kiwi', 'avocado', 'orange', 'cherry', 'strawberry'] nut: ['peanut', 'walnut', 'almond'] seed: ['sunflower seed', 'rye grain', 'sesame', 'pumpkin seed'] vegetable: ['cucumber', 'lettuce'] """ # Variant 2: Using defaultdict from collections import defaultdict dd = defaultdict(list) for k, v in foods: dd[k].append(v) for k, v in dd.items(): print(': '.join([k, str(v)])) """ flower: ['Chrysanthemum', 'Rose', 'Dahlia', 'Iris'] nut: ['peanut', 'walnut', 'almond'] vegetable: ['cucumber', 'lettuce'] seed: ['sunflower seed', 'rye grain', 'sesame', 'pumpkin seed'] fruit: ['kiwi', 'avocado', 'orange', 'cherry', 'strawberry'] """ # Variant 3: Using pandas import pandas as pd d = dict((v, k) for k, v in foods) df = pd.DataFrame(list(d.items()), columns=['Item', 'Type']) for group, items in df.groupby('Type'): print(': '.join([group, str(items['Item'].tolist())])) """ flower: ['Rose', 'Dahlia', 'Chrysanthemum', 'Iris'] fruit: ['kiwi', 'avocado', 'orange', 'cherry', 'strawberry'] nut: ['peanut', 'walnut', 'almond'] seed: ['sesame', 'sunflower seed', 'pumpkin seed', 'rye grain'] vegetable: ['lettuce', 'cucumber'] """