jean_pierre
jean_pierre

Reputation: 47

Create a dictionary from a list of tuples

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

Answers (4)

yatu
yatu

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

SomeDude
SomeDude

Reputation: 14238

You could do something like below:

  • Go through each tuple in the list for e.g. (1, 2, 3) ( for t in l )
  • Then check if the first element in the tuple is in the dictionary i.e. dictionary has already a key with that value? ( if t[0] in s )
  • If yes, then update the value which is a set with the new elements in the tuple excluding the first element - because first element is the key ( s[t[0]].update(set(t[1:])) )
  • It not, then create an item in the dictionary with key = first element and value = set( remaining elements ) ( 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

Riccardo Bucco
Riccardo Bucco

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

SergioGM
SergioGM

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

Related Questions