【问题标题】:Sum dictionary values in python by specific keys通过特定键对python中的字典值求和
【发布时间】:2017-06-17 08:53:32
【问题描述】:

我有以下名为“资产”的字典列表:

assets = [
{
    "type": "site",
    "pcd_sector_id": 1,
    "cells": 3,
    "technology": "LTE"
},
{
    "type": "site",
    "pcd_sector_id": 2,
    "cells": 5,
    "technology": "LTE-Advanced"
},
{
    "type": "site",
    "pcd_sector_id": 2,
    "cells": 3,
    "technology": "LTE"
}
]

我想总结所有可能技术的“单元”(有 >50 个)。我查看了很多问题,但我找不到任何基于字符串变量的总和数值。

我知道如何在 Pandas 中轻松做到这一点,但我正在寻找一个纯 python 解决方案。

编辑:根据反馈,我对问题和数据进行了一些更改。所需的输出将具有每个邮政编码扇区按技术划分的单元数:

aggregated = [
{
"pcd_sector_id": 1,
"LTE": 3,
"LTE-Advanced": 0
}
{
"pcd_sector_id": 2,
"LTE": 3,
"LTE-Advanced": 5
}
]

【问题讨论】:

  • 你能提供你正在寻找的输出吗?

标签: python dictionary sum


【解决方案1】:

您要做的是首先检索单个列表中的所有“单元格”项目:

cells = [d['cells'] for d in assets]

# or

import operator

cells = map(operator.itemgetter('cells'), assets)

然后使用内置的sum 函数将它们相加:

sum(d['cells'] for d in assets)

# or

sum(map(operator.itemgetter('cells'), assets))

这两种方法都适用于较小的列表(我认为顶部的方法会更快),但底部的方法对于大型列表肯定更快:

$python3 -m timeit "assets = [{'cells': 1}] * 1000; import operator" "sum(d['cells'] for d in assets)"
10000 loops, best of 3: 67.4 usec per loop
$python3 -m timeit "assets = [{'cells': 1}] * 1000; import operator" "sum(map(operator.itemgetter('cells'), assets))"
10000 loops, best of 3: 47.5 usec per loop

【讨论】:

    【解决方案2】:

    您需要检索字典的特定列并对其进行总结。

    count =0
    for i in assets:
        count = count + i['cells']
    

    >>Demo<<

    【讨论】:

      【解决方案3】:

      一线解决方案:

      >>> sum([asset['cells'] for asset in assets])
      

      【讨论】:

      • 删除外部[ ]。否则会建立一个没有必要的临时列表。
      猜你喜欢
      • 2018-04-16
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多