通过对相同键的值求和,从元组列表创建dict

2024-10-01 22:44:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下清单:

[(2018, '2', '172767270', '202', 'gege', 'French'),
 (2012, '212', '56007072', '200', 'cdadcadc', 'Minangkabou'),
 (2013, 'J21', '186144990', '200', 'sacacs', 'Latin'),
 ...
]

我希望输出是基于最后一列中的键和第三列中的值之和的字典

例如,对于总和为172767270+1374767888=1547535158的(172767270,法语)和(1374767888,法语),字典将具有以下键值对:

dic = {'French': 1547535158, ...}

最终的结果是:

dic = {'French': 324213424, 'Latin': 34234242, ...}

Tags: 字典键值french总和latindicgegesacacs
3条回答

首先,我们必须添加基于语言的所有值

lang = [(2018, '2', '172767270', '202', 'gege', 'French'),(2012, '212', '56007072', '200', 'cdadcadc', 'Minangkabou'),(2013, 'J21', '186144990', '200', 'sacacs', 'Latin')]
dic = {}
for l in lang:
    dic[l[5]] = dic.get(l[5], 0) + int(l[2])

现在我们有了一本所有语言的第三列总和的词典。现在让我们对其进行排序,以获得前5名

dic2 = dict(sorted(dic.items(),key=dict.get, reverse=True)[:5])

现在,dic2只有第三列总和最高的前5种语言

我假设你有一个元组列表。正如您所提到的,我们不需要导入任何模块。如果键存在,则使用dict.get()方法查找该键的值;如果键不存在,则使用0作为默认值

例如,如果字典中没有“French”,get()将返回0,否则它将返回与“French”关联的值

然后我们可以简单地将第三列的值添加到.get()返回的值中

dict={}
for tup in lst:
    dict[tup[5]]=dict.get(tup[5],0)+ int(tup[2])

#to get top 5 values
dict2={}
for i in sorted(dict, key=dict.get, reverse=True)[:5]:
    dict2[i]=dict[i]

list = []  #define list here
dict_out = {} #output dictionary

def get_sum(name):
    summed = 0
    for value in list:
        if value[-1] == name:
            summed += int(value[2])
    return summed 

for value in list:
    if value[-1] not in dict_out:
        dict_out[value[-1]] = get_sum(value[-1])[:4]

相关问题 更多 >

    热门问题