Reputation: 47
I got a list of multiple tuples like it for example :
[(1,2,3),(1,10,11),(5,7,8)]
and my aim is to obtain it :
{1:{2,3,10,11},5:{7,8}}
thanks for reading me
Thanks, it workds but I must have only unique value, and I don't want to have list
Upvotes: 1
Views: 185
Reputation: 88236
You can use a defaultdict
:
l = [(1,2,3),(1,10,11),(5,7,8)]
from collections import defaultdict
d = defaultdict(set)
for k,*t in l:
d[k].update(t)
Or with a python dict
we can use dict.setdefault
:
d = dict()
for k,*t in l:
d.setdefault(k, set()).update(t)
print(d)
{1: {10, 11, 2, 3}, 5: {8, 7}}
Upvotes: 3
Reputation: 14238
You could do something like below:
for t in l
)if t[0] in s
)s[t[0]].update(set(t[1:]))
)s[t[0]] = set(t[1:])
) l = [(1,2,3),(1,10,11),(5,7,8)]
s = {}
for t in l:
if t[0] in s:
s[t[0]].update(set(t[1:]))
else:
s[t[0]] = set(t[1:])
print(s)
Output:
{1: {10, 11, 2, 3}, 5: {8, 7}}
If you want your set (value) in each item in the dictionary to be sorted, you could use a ordered-set
or some manipulation on OrderedDict
Upvotes: 2
Reputation: 15364
Here is a one-line solution using pandas
:
import pandas as pd
lst = [(1, 2, 3), (1, 10, 11), (5, 7, 8)]
result = (pd.DataFrame(lst).groupby(0).agg(set)
.apply(lambda x: x[1].union(x[2]), axis=1).to_dict())
Basically, first you group all your tuples having the same first element. Then you build sets with the remaining elements of the tuples. You use the union
operation on sets sharing the first element. Finally you build the dictionary from the resulting dataframe.
Here is the result:
>>> result
{1: {11, 3, 2, 10}, 5: {8, 7}}
Upvotes: 0
Reputation: 679
For example:
tuples=[(1,2,3),(1,4,5),(2,4,7)]
keys=set([i[0] for i in tuples])
result={}
for key in keys:
dummy=[]
for t in tuples:
if t[0]==key:
dummy.append(t[1:])
result[key]=dummy
Edit: reducing loops
result={}
for k, *t in tuples:
if k not in result:
result[k] = t
else:
result[k].extend(t)
Upvotes: 0