Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to join second elements in tuples using group by first element python

I have a list of tuples

a = [('name', 'color'),('fruit', 'color'),('thing', 'type'),('sport', 'type')]

I want to join first elements grouped by second element. The output should look like.

a = [('name fruit', 'color'),('thing sport', 'type')]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can create dict with the key that you want to group and add value to list base key. For this approach, you can use collections.defaultdict or if you don’t want to import anything you can use dict.setdefault.

from collections import defaultdict


a = [('name', 'color'),('fruit', 'color'),('thing', 'type'),('sport', 'type')]
res = defaultdict(list)
res_2 = {}

for tpl in a:
    res[tpl[1]].append(tpl[0])
    res_2.setdefault(tpl[1], []).append(tpl[0])

# Now you can use `res_2` instead of `res`
lst = [(' '.join(v), k) for k,v  in res.items()]
print(lst)

Another option can be to use itertools.groupby. For this approach, you can set with which value of your tuple you want to group. (Because you want to group the base second value of each tuple you can set the key of groupby like lambda x: x[1].)

from itertools import groupby

res = []
for key, group in itertools.groupby(a, lambda x: x[1]):
    res.append((' '.join(tpl[0] for tpl in group), key))
print(res)

Output:

[('name fruit', 'color'), ('thing sport', 'type')]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading