Create a dictionary from a tuple with a similar key

Viewed 46

Suppose I have these tuples:

('eggs', 20, 30)
('eggs', 40, 23)
('eggs', 10, 24)
('apple', 2, 22)
('apple', 42, 3)

I want a dictionary to look like this:

{
eggs: [[20, 30], [40,23], [10,24]], 
apple: [[2,22], [42,3]]
}

How would I get this

I tried doing this:

dic = {}
for d in data:
   dic[d[0]] += [[d[1], d[2]]

#d[0] being eggs or apple, d[1] and d[2] being the numbers


3 Answers

Try this,

>>> t = [('eggs', 20, 30), ('eggs', 40, 23), ('eggs', 10, 24), ('apple', 2, 22), ('apple', 42, 3)]

>>> d = {}        
>>> for k, v1, v2 in t:
    d.setdefault(k,[]).append([v1,v2])

Output:

>>> d             
{'eggs': [[20, 30], [40, 23], [10, 24]], 'apple': [[2, 22], [42, 3]]}

Your approach is correct if you use defaultdict.

from collections import defaultdict

dic = defaultdict(list)

for d in datas:
   dic[d[0]] += [[d[1], d[2]]]

print (dic)

#defaultdict(<class 'list'>, {'eggs': [[20, 30], [40, 23], [10, 24]], 'apple': [[2, 22], [42, 3]]})

Similar to @shaikmoeed's answer, but with iterator unpacking:

dic = {}
for key, *values in lst:
    dic.setdefault(key, []).append(values)

so that given:

lst = [
    ('eggs', 20, 30),
    ('eggs', 40, 23),
    ('eggs', 10, 24),
    ('apple', 2, 22),
    ('apple', 42, 3)
]

dic becomes:

{'eggs': [[20, 30], [40, 23], [10, 24]], 'apple': [[2, 22], [42, 3]]}
Related