Build a dictionary containing for each keys, a set of associate values from a list of tuples

Viewed 76

I have a list of tuples like this:

list = [(1,2),(1,3),(1,5),(0,8),(0,9),(0,1),(3,6),(3,7)]

I want to build a dictionary with sets of associate values like this:

result = {1:{2,3,5},0:{8,9,1},3:{6,7}}

I have this code:

return {x:y for (x,y) in list}

result = {1: 5, 0: 1, 3: 7}

But I have only the last value, I want all associate values in a set.

Thanks in advance

5 Answers

defaultdict could add value for a key without checking existence

from collections import defaultdict
mylist = [(1,2),(1,3),(1,5),(0,8),(0,9),(0,1),(3,6),(3,7)]
result = defaultdict(list)
for item in mylist:
    result[item[0]].append(item[1])

This should help u:

lst = [(1,2),(1,3),(1,5),(0,8),(0,9),(0,1),(3,6),(3,7)]
result= {}

[result.setdefault(x, set()).add(y) for x,y in lst]

print(result)

Output:

{1: {2, 3, 5}, 0: {8, 9, 1}, 3: {6, 7}}

SOLUTION:
This code snippet should solve your problem statement:

lst = [(1,2),(1,3),(1,5),(0,8),(0,9),(0,1),(3,6),(3,7)]

output_dict = dict()
[output_dict[t[0]].add(t[1]) if t[0] in list(output_dict.keys()) else output_dict.update({t[0]: {t[1]}}) for t in lst]
print(output_dict)

OUTPUT:

{1: {2, 3, 5}, 0: {8, 9, 1}, 3: {6, 7}}

Incase if you want one liner:

In [10]: original_list = [(1,2),(1,3),(1,5),(0,8),(0,9),(0,1),(3,6),(3,7),(1,2)]

In [11]: {x: {r for(q, r) in original_list if q == x} for (x, y) in original_list}
Out[11]: {1: {2, 3, 5}, 0: {1, 8, 9}, 3: {6, 7}}

Here it is:

result = {}

for x, y in list:
    if x not in result:
        result[x] = []
    result[x].append(y)

print(result)
Related