【问题标题】:Create a dict from a list of tuples by summing values for the same keys [duplicate]通过对相同键的值求和来从元组列表中创建一个字典 [重复]
【发布时间】:2020-05-30 09:05:32
【问题描述】:

我有这个清单:

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

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

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

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

最终的结果会是这样的:

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

【问题讨论】:

  • 您的问题是什么?你只是在问代码,而不是在问问题。

标签: python list dictionary tuples


【解决方案1】:
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]

【讨论】:

    【解决方案2】:

    我假设您有一个元组列表。正如您所提到的,我们不需要导入任何模块。如果键存在,则使用 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]
    
    

    【讨论】:

    • 问题是,他只想要前 5 种语言的总和,而不是全部
    • 抱歉,已更正答案以仅获得前 5 个值
    【解决方案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])
    

    现在我们有了一个字典,其中包含所有语言的第 3 列的总和。现在让我们对其进行排序以获得前 5 名。

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

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

    【讨论】:

      【解决方案4】:

      如果你想根据语言得到第三列的总和,那么:

      d = defaultdict(int)
      l = [(2018, '2', '172767270', '202', 'gege', 'French'),(2018, '2', '172763270', '202', 'gege', 'English'),(2018, '2', '17167270', '202', 'gege', 'Spanish'),
      (2012, '212', '56007072', '200', 'cdadcadc', 'Minangkabou'),(2018, '2', '1727672', '202', 'gege', 'Arabic'),(2013, 'J21', '186144990', '200', 'sacacs', 'Latin'),(2017, '2', '1374767888', '202', 'gege', 'French')]
      
      for elem in l:
          d[elem[5]]+= int(elem[2])
      
      d
      

      输出:

      defaultdict(int,
                  {'Arabic': 1727672,
                   'English': 172763270,
                   'French': 1547535158,
                   'Latin': 186144990,
                   'Minangkabou': 56007072,
                   'Spanish': 17167270})
      

      之后,如果你只想要前 5 名,你可以这样做:

      dict(sorted(list(d.items()),key= lambda x:x[1],reverse=True)[:5])
      

      输出:

       {'English': 172763270,
       'French': 1547535158,
       'Latin': 186144990,
       'Minangkabou': 56007072,
       'Spanish': 17167270}
      

      【讨论】:

        【解决方案5】:

        如果我理解正确,你想要一个 for 循环会做什么。

        mylist = [] #your list as given above
        mydict = {} #here we'll save the values
        
        for(item in mylist):
            #read out the values needed
            value = item[2]
            language = item[-1] #item[6] would also work.
        
            #check if language is already in. If not? Than make it.
            if(language not in mydict):
                mydict[language] = 0
        
            #Add value to correct dictionary item.
            mydict[language] += value
        

        比你有完整的字典。然后根据值在字典中查找前 5 项。

        def myfunc(elem): #returns second entry of tuple.
            return elem[1]
        
        #get the list of all the entries
        allEntries = list(mydict.items()) #list of tuples
        sortedList = sorted(allEntries, key=myfunc, reverse=True) #list sorted on values
        
        print(dict(sortedList[:5])) #dictionary of first five items of the sorted list
        

        我希望这是你想要的。

        【讨论】:

          猜你喜欢
          • 2019-09-21
          • 1970-01-01
          • 2018-10-20
          • 2021-12-07
          • 1970-01-01
          • 2016-06-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多