【问题标题】:How can I sum up dictionaries in a list (python)?如何总结列表中的字典(python)?
【发布时间】:2022-01-24 06:28:03
【问题描述】:

我有以下列表,其中包含几个字典。

item_list = [{'item': 'apple', 'amount': 200}, {'item': 'apple', 'amount': 150}, {'item': 'orange', 'amount': 300}]

我想总结每个项目的金额。不使用 Counter 怎么办?

期望的输出是

[{'item': 'apple', 'amount': 350},  {'item': 'orange', 'amount': 300}]

【问题讨论】:

  • 您在解决问题时遇到了什么特殊问题?请在问题中发布。
  • 你不想使用Counter(它在这里并不适用),但你可以使用collections.defaultdict之类的东西吗?

标签: python list dictionary


【解决方案1】:

您可以使用临时字典来保存总和并重新创建原始结构

from collections import defaultdict

item_list = [{'item': 'apple', 'amount': 200}, {'item': 'apple', 'amount': 150}, {'item': 'orange', 'amount': 300}]

sumdict = defaultdict(int)

for item in item_list:
  sumdict[item['item']] += item['amount']

result = [{'item': k, 'amount': v} for k,v in sumdict.items()]
print(result)

【讨论】:

    【解决方案2】:

    不使用任何模块,按项目名称创建索引字典,然后提取值列表:

    new_item_dict = {}
    for i in item_list:
        d = new_item_dict.setdefault(i['item'], {'item': i['item'], 'amount': 0})
        d['amount'] += i['amount']
    new_item_list = list(new_item_dict.values())
    

    输出:

    >>> new_item_list
    [{'item': 'apple', 'amount': 350},
     {'item': 'orange', 'amount': 300}]
    

    【讨论】:

    • 非常感谢您的回答!!我现在明白了。真的很感激。
    【解决方案3】:

    您可以先选择您的项目,然后查看每个项目并获取它们的数量:

    item_list = [{'item': 'apple', 'amount': 200}, {'item': 'apple', 'amount': 150}, {'item': 'orange', 'amount': 300}]
    keys = set([ele['item'] for ele in item_list]) # Use set to get the unique keys
    d = dict()
    for k in keys:
        d[k] = sum( [ ele['amount'] for ele in item_list if ele['item'] == k ] )
    >>> {'orange': 300, 'apple': 350}
    

    第一个获取每个字典中所有项目的唯一集合。 新变量d 是一个新字典,其中键是第一个字典的项。 最后总结所有项目。

    或其他格式(但您可以随意更改):

    item_list = [{'item': 'apple', 'amount': 200}, {'item': 'apple', 'amount': 150}, {'item': 'orange', 'amount': 300}]
    keys = set([ele['item'] for ele in item_list]) # Use set to get the unique keys
    d = list()
    for k in keys:
        d.append({'item': k, 'amount': sum( [ ele['amount'] for ele in item_list if ele['item'] == k ] ) } )
    >>> [{'item': 'orange', 'amount': 300}, {'item': 'apple', 'amount': 350}]
    

    【讨论】:

      【解决方案4】:

      你应该试试这样的:

      itemToSum = 'apple' 
      sum = 0
      
      for dictionary item_list:
          if itemToSum in dictionary.values():
              amount = dictionary.get(item_list('amount')
              sum = sum + amount
      

      基本上,您所做的是检查数组中的每个字典是否具有您要计算的值,如果是,则计算该值。其他答案可能建议使用外部库,但您可以在不使用任何库的情况下完成工作

      【讨论】:

      • 最好不要使用内置名称。 sum 就是其中之一。
      • @AivarPaalberg 感谢您的建议。已注明。
      【解决方案5】:

      这可能有点矫枉过正,但你可以使用 Pandas。

      import pandas as pd
      
      item_list = [
          {'item': 'apple', 'amount': 200}, 
          {'item': 'apple', 'amount': 150},
          {'item': 'orange', 'amount': 300}
      ]
      
      df = pd.DataFrame(item_list)
      totals = df.groupby("item").sum()
      summed_list = [{'item': item, 'amount': values['amount']} 
                     for item, values in totals.iterrows()]
      print(summed_list)
      

      或者:

      df = pd.DataFrame(item_list)
      totals = df.groupby("item").sum()
      summed_list = totals.reset_index().to_dict('records')
      print(summed_list)
      

      【讨论】:

        【解决方案6】:
        from collections import defaultdict
        
        item_amount = defaultdict(lambda: 0)
        
        for item in item_list:
            name, amount = item['item'], item['amount']
            item_amount[name] += amount
        
        item_amount = [{'item': name, 'amount': amount} for name, amount in item_amount.items()]
        
        item_amount
        

        【讨论】:

          【解决方案7】:

          一种方法是:“尝试将金额添加到项目,如果没有项目则添加记录和项目”。这需要对 item_list 进行一次迭代并保留整个记录(item_list 中的字典)并依赖于列表索引(输出列表中的字典索引对应于所见列表中的项目索引):

          item_list = [{'item': 'apple', 'amount': 200}, 
                       {'item': 'apple', 'amount': 150}, 
                       {'item': 'orange', 'amount': 300}]
          
          output = []
          seen = []
          
          for item in item_list:
              try:
                  output[seen.index(item['item'])]['amount'] += item['amount']
              except ValueError:
                  output.append(item)
                  seen.append(item['item'])
          

          【讨论】:

            猜你喜欢
            • 2023-01-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-10-08
            • 2018-10-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多