baobobs
baobobs

Reputation: 703

Merging tuples with identical items within a tuple in Python

I realize this is a basic question but I cannot get this to work. I have the following tuple:

t = (('apple', 'banana'), ('apple', 'carrot'), ('banana', 'carrot'))

I want the first item within every tuple in t to be unique, and to merge the second item of every duplicate together into a dictionary.

t = {('apple': 'banana', 'carrot'), ('banana': 'carrot')}

Not surprisingly, this doesn't work:

t = dict(zip(set(t[0]),t[1]))

This is the result:

{'apple': 'apple', 'banana': 'carrot'}

Upvotes: 0

Views: 257

Answers (3)

Ali-Akber Saifee
Ali-Akber Saifee

Reputation: 4616

the setdefault method of dicts come in handy for cases like this:

t = (('apple', 'banana'), ('apple', 'carrot'), ('banana', 'carrot'))
d = {}
[d.setdefault(k,[]).append(v) for k,v in t]

Upvotes: 1

Cris Stringfellow
Cris Stringfellow

Reputation: 3808

Here is a complete solution (Edit: Now Python 3 compatible):

import functools
t = (('apple', 'banana'), ('apple', 'carrot'), ('banana', 'carrot'))

def insert(d,k,v):
        d[k] = (v,) if k not in d else d[k]+(v,)
        return d

z = functools.reduce(lambda d,ti: insert(d,*ti),t,{})

def flat(tpl):
        return sum([(x,) if not isinstance(x,tuple) else x for x in tpl],())

result = [flat(x) for x in z.items()]

Yields :

[('apple', 'banana', 'carrot'), ('banana', 'carrot')]

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213321

I think, you should use a dict here (or rather a defaultdict). Where key of the dict would be the first element of your inner tuples - tup[0].

This is what you want:

>>> t = (('apple', 'banana'), ('apple', 'carrot'), ('banana', 'carrot'))
>>>
>>> from collections import defaultdict
>>> 
>>> temp_dict = defaultdict(tuple)
>>> 
>>> for tup in t:
        temp_dict[tup[0]] += tup[1:]  


>>> temp_dict
defaultdict(<type 'tuple'>, {'apple': ('banana', 'carrot'), 'banana': ('carrot',)})

>>> {key:value for key, value in temp_dict.items()}
{'apple': ('banana', 'carrot'), 'banana': ('carrot',)}

Upvotes: 3

Related Questions