python-3.x - 如何对字典中相同键的值求和?

标签 python-3.x dictionary sum key-value

假设我的字典:mydict = [{"red":6}, {"blue":5}, {"red":12}]

这是我到目前为止所做的:

for key, value in mydict() :
    if key == mydict.keys():
        key[value] += value
    else:
        print (key, value)

我认为我的理解不太正确(被困了几个小时),但我希望输出如下所示:

blue 5
red 18

red 18
blue 5

最佳答案

我不推荐这样做,因为它会导致设计困惑:

class MyDict(dict):

    def __setitem__(self, key, value):
        if key in self:
            super().__setitem__(key, self[key] + value)
        else:
            super().__setitem__(key, value)

>>> d = MyDict({'red': 6, 'blue': 5})
>>> d['red'] = 12
>>> d
{'red': 18, 'blue': 5}
>>> d['blue']
5
>>> d['red']
18
>>> d['red'] = 8
>>> d
{'red': 26, 'blue': 5}

编辑:我看到你更改了初始对象...

>>> mydict = [{"red":6}, {"blue":5}, {"red":12}]
>>> sum(d.get('red', 0) for d in mydict)
18

关于python-3.x - 如何对字典中相同键的值求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21518271/

相关文章:

python - 查找作为列表列表输入的 N x N 矩阵的行列式 - "list index out of range"

python - 检查 ansible 上 Jinja2 模板中的字典中是否存在 key

r - 对具有相似名称的列逐行求和

python - pandas DataFrame 中不均匀大小的列的总和

php - SUM 行字段 MEDOO

python - 基于正则表达式的随机字符串生成-Python

windows - 安装 Python 3 后安装 Python 2.7

python - 如何对python字典的每个键的值进行排序?

javascript - react 练习 : two arrays rendered by two children and displayed next to each other (Matching indexes) in parent

c# - 如何制作具有不同返回码的自定义词典?