How to keep your original dict while adding counter

As I understand it, I know when I call the Counter

hidden dict. This dict includes the keys value, zero will disappear.

from collections import Counter

a = {"a": 1, "b": 5, "d": 0}
b = {"b": 1, "c": 2}

print Counter(a) + Counter(b)

      

If I want to keep my keys, how do I do it?

This is my expected output:

Counter({'b': 6, 'c': 2, 'a': 1, 'd': 0})

      

+3


source to share


4 answers


You can also use update()

Counter method instead of operator +

, example -

>>> a = {"a": 1, "b": 5, "d": 0}
>>> b = {"b": 1, "c": 2}
>>> x = Counter(a)
>>> x.update(Counter(b))
>>> x
Counter({'b': 6, 'c': 2, 'a': 1, 'd': 0})

      



update()

the function adds the number of samples instead of replacing them, and it does not remove the zero value. We can also do Counter(b)

and then update with Counter(a)

, Example -

>>> y = Counter(b)
>>> y.update(Counter(a))
>>> y
Counter({'b': 6, 'c': 2, 'a': 1, 'd': 0})

      

+4


source


Unfortunately, when adding two counters, only positive counter elements are used.

If you want to store zero-numbered elements, you can define a function like this:



def addall(a, b):
    c = Counter(a)          # copy the counter a, preserving the zero elements
    for x in b:             # for each key in the other counter
        c[x] += b[x]        # add the value in the other counter to the first
    return c

      

+1


source


You can just subclass Counter

and customize its method __add__

:

from collections import Counter


class MyCounter(Counter):
    def __add__(self, other):
        """Add counts from two counters.
        Preserves counts with zero values.

        >>> MyCounter('abbb') + MyCounter('bcc')
        MyCounter({'b': 4, 'c': 2, 'a': 1})
        >>> MyCounter({'a': 1, 'b': 0}) + MyCounter({'a': 2, 'c': 3})
        MyCounter({'a': 3, 'c': 3, 'b': 0})
        """
        if not isinstance(other, Counter):
            return NotImplemented
        result = MyCounter()
        for elem, count in self.items():
            newcount = count + other[elem]
            result[elem] = newcount
        for elem, count in other.items():
            if elem not in self:
                result[elem] = count
        return result


counter1 = MyCounter({'a': 1, 'b': 0})
counter2 = MyCounter({'a': 2, 'c': 3})

print(counter1 + counter2)  # MyCounter({'a': 3, 'c': 3, 'b': 0})

      

+1


source


I'll help Anand S Kumar

make more additional explanations.

Even if your dict contains a negative value, it still preserves your keys.

from collections import Counter

a = {"a": 1, "b": 5, "d": -1}
b = {"b": 1, "c": 2}

print Counter(a) + Counter(b)
#Counter({'b': 6, 'c': 2, 'a': 1})

x = Counter(a)
x.update(Counter(b))
print x
#Counter({'b': 6, 'c': 2, 'a': 1, 'd': -1})

      

0


source







All Articles