close

How to add or increment single item of the Python Counter class

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to add or increment single item of the Python Counter class in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to add or increment single item of the Python Counter class?

  1. How to add or increment single item of the Python Counter class?

    Well, you don't really need to use methods of Counter in order to count, do you? There's a += operator for that, which also works in conjunction with Counter.

  2. add or increment single item of the Python Counter class

    Well, you don't really need to use methods of Counter in order to count, do you? There's a += operator for that, which also works in conjunction with Counter.

Method 1

Well, you don’t really need to use methods of Counter in order to count, do you? There’s a += operator for that, which also works in conjunction with Counter.

c = Counter()
for item in something:
    if item.has_some_property:
        c[item.property] += 1
    elif item.has_some_other_property:
        c[item.other_property] += 1
    elif item.has_some.third_property:
        c[item.third_property] += 1

Method 2

>>> c = collections.Counter(a=23, b=-9)

You can add a new element and set its value like this:

>>> c['d'] = 8
>>> c
Counter({'a': 23, 'd': 8, 'b': -9})

Increment:

>>> c['d'] += 1
>>> c
Counter({'a': 23, 'd': 9, 'b': -9} 

Note though that c['b'] = 0 does not delete:

>>> c['b'] = 0
>>> c
Counter({'a': 23, 'd': 9, 'b': 0})

To delete use del:

>>> del c['b']
>>> c
Counter({'a': 23, 'd': 9})

Counter is a dict subclass

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read