Reputation: 27
I am trying to convert my list of tuples 'L' into a dictionary. I am trying to write some code that will add element[5] to my value when the same key (in element[1]) is looped instead of replacing the value.
L = [('super mario land 2: 6 golden coins','GB',1992,'adventure','nintendo',11180000.0),
('sonic the hedgehog 2', 'GEN', 1992, 'platform', 'sega', 6020000.0),
("kirby's dream land", 'GB', 1992, 'platform', 'nintendo', 5130000.0),
("the legend of zelda: link's awakening",'GB',1992,'action','nintendo',3840000.0),
('mortal kombat', 'GEN', 1992, 'fighting', 'arena entertainment', 2670000.0)]
D = {}
for element in L:
D[element[1]] = element[5]
Dictionary I want:
D = { 'GB': 20150000.0,
'GEN': 8690000 }
Upvotes: 0
Views: 62
Reputation: 8174
Only for fun, one line solution
L = [('super mario land 2: 6 golden coins','GB',1992,'adventure','nintendo',11180000.0), ('sonic the hedgehog 2', 'GEN', 1992, 'platform', 'sega', 6020000.0), ("kirby's dream land", 'GB', 1992, 'platform', 'nintendo', 5130000.0), ("the legend of zelda: link's awakening",'GB',1992,'action','nintendo',3840000.0), ('mortal kombat', 'GEN', 1992, 'fighting', 'arena entertainment', 2670000.0)]
from itertools import groupby
from operator import itemgetter
from functools import reduce
dict([(K,reduce(lambda x,y:x+y,[e[-1] for e in T])) for K,T in groupby(sorted(L,key=itemgetter(1)),itemgetter(1))])
you get,
{'GB': 20150000.0, 'GEN': 8690000.0}
Upvotes: 0
Reputation: 2819
Maybe:
for element in L:
if not element[1] in D.keys():
D[element[1]] = element[5]
else:
D[element[1]] += element[5]
Upvotes: 0
Reputation: 608
D = {}
for element in L:
if element[1] in D:
D[element[1]] += element[5]
else:
D[element[1]] = element[5]
Upvotes: 0
Reputation: 39414
You can use a defaultdict
for this:
from collections import defaultdict
L = [('super mario land 2: 6 golden coins','GB',1992,'adventure','nintendo',11180000.0),
('sonic the hedgehog 2', 'GEN', 1992, 'platform', 'sega', 6020000.0),
("kirby's dream land", 'GB', 1992, 'platform', 'nintendo', 5130000.0),
("the legend of zelda: link's awakening",'GB',1992,'action','nintendo',3840000.0),
('mortal kombat', 'GEN', 1992, 'fighting', 'arena entertainment', 2670000.0)]
D = defaultdict(float)
for element in L:
D[element[1]] += element[5]
print(D)
Output as requested
Upvotes: 1