zzrb
zzrb

Reputation: 77

Create a dictionary from a tuple with a similar key

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


Upvotes: 3

Views: 49

Answers (3)

Henry Yik
Henry Yik

Reputation: 22493

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]]})

Upvotes: 3

blhsing
blhsing

Reputation: 106465

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]]}

Upvotes: 2

shaik moeed
shaik moeed

Reputation: 5785

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]]}

Upvotes: 3

Related Questions