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

2019-06-08 03:07发布

Supose my dictionary: mydict = [{"red":6}, {"blue":5}, {"red":12}]

This is what I've done so far:

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

I don't think I'm getting it quite right (been stuck for hours), but I want the output to look like this:

blue 5
red 18

or

red 18
blue 5

2条回答
淡お忘
2楼-- · 2019-06-08 03:35

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

查看更多
走好不送
3楼-- · 2019-06-08 03:59

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
查看更多
登录 后发表回答