Convert a list of tuples to a dictionary, based on tuple values

Viewed 103

I have a little problem, maybe dumb, but it seems I can't solve it.

I have a list of objects that have members, but let's say my list is this:

l = [(1, 'a'), (2, 'a'), (1, 'b'), (1, 'c'), (3, 'a')]

I want to "gather" all elements based on the value I choose, and to put them into a dictionary based on that value/key (can be both the first or the second value of the tuple).

For example, if I want to gather the values based on the first element, I want something like that:

{1: [(1, 'a'), (1, 'b'), (1, 'c')], 2: [(2, 'a')], 3: [(3, 'a')]}

However, what I achieved until now is this:

>>> {k:v for k,v in zip([e[0] for e in l], l)}
{1: (1, 'c'), 2: (2, 'a'), 3: (3, 'a')}

Can somebody please help me out?

4 Answers

My first thought would be using defaultdict(list) (efficient, in linear time), which does exactly what you were trying to do:

from collections import defaultdict
dic = defaultdict(list)
l = [(1, 'a'), (2, 'a'), (1, 'b'), (1, 'c'), (3, 'a')]
for item in l:
    dic[item[0]].append(item)

output

defaultdict(list,{1: [(1, 'a'), (1, 'b'), (1, 'c')], 2: [(2, 'a')], 3: [(3, 'a')]})

Here with list comprehension, oneliner:

l = [(1, 'a'), (2, 'a'), (1, 'b'), (1, 'c'), (3, 'a')]

print (dict([(x[0], [y for y in l if y[0] == x[0]]) for x in l]))

Output:

{1: [(1, 'a'), (1, 'b'), (1, 'c')], 2: [(2, 'a')], 3: [(3, 'a')]}

Here you go:

l = [(1, 'a'), (2, 'a'), (1, 'b'), (1, 'c'), (3, 'a')]
output_dict = dict()

for item in l:
    if item[0] in output_dict:
        output_dict[item[0]].append(item)
        continue
    output_dict[item[0]] = [item]

print(output_dict)

First create a dico with list inside :

l = [(1, 'a'), (2, 'a'), (1, 'b'), (1, 'c'), (3, 'a')]
dico={}
for i in range(4):
    dico[i]=[]

Then fill this dico

for i in l:
    dico[i[0]].append(i)
Related