简体   繁体   English

将元组列表转换为字典

[英]Convert list of tuples into a dictionary

I am trying to convert my list of tuples 'L' into a dictionary.我正在尝试将我的元组列表“L”转换为字典。 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.我正在尝试编写一些代码,当循环相同的键(在元素 [1] 中)而不是替换值时,将元素 [5] 添加到我的值中。

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 }

You can use a defaultdict for this:您可以为此使用defaultdict

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 Output 按要求

D = {}
for element in L:
    if element[1] in D:
        D[element[1]] += element[5]
    else:
        D[element[1]] = element[5]

Maybe:也许:

for element in L:
    if not element[1] in D.keys():
         D[element[1]] = element[5]
     else:
         D[element[1]] += element[5]

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM