How to sum values of the same key in a dictionary?

杀马特。学长 韩版系。学妹 提交于 2019-12-06 19:39:27

I do not recommend this since it results a messy design:

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}

EDIT: I see you changed the initial object...

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

you cannot have a dictionary with same keys.... For definition keys are unique! and the last assignement of a key, overwrite the previous one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!