Working with python collections Counter

Working with Counter:

        Counter is very useful in counting occurrences of hashable objects. The elements are stored as dictionary keys and counts are stored as dictionary values. 


    To count the frequency of a character in a given string.

    >>>  from counter import Counter
    >>>  str = "python is an easy to learn powerful programming language" 
    >>>  c = Counter(str.replace(' ', ''))
           Counter({'a': 6, 'n': 5, 'e': 4, 'g': 4, 'o': 4, 'r': 4, 'l': 3, 'p': 3, 'i': 2, 'm': 2, 's': 2, 'u': 2, 't': 2, 'y': 2, 'h': 1, 'f': 1, 'w': 1})

Initializing Counter:

     We can initialize counter in three ways.

    >>> import collections
    >>> collections.Counter(['a','b','c','d','e'])
        Counter({'a': 1, 'c': 1, 'b': 1, 'e': 1, 'd': 1})
    >>> collections.Counter({'a':2,'b':1,'c':-2,'d':2,'e':0})
        Counter({'a': 2, 'd': 2, 'b': 1, 'e': 0, 'c': -2})
    >>> collections.Counter(a=2,b=1,c=-2,d=2,e=0)
        Counter({'a': 2, 'd': 2, 'b': 1, 'e': 0, 'c': -2})

Creating and Updating Counters:

   >>> import collections
   >>> c = collections.Counter()              # initializing empty counter
   >>> c.update('xyzzzxy')                    # adding elements to empty counter or updating empty counter
   >>> c
       Counter({'z': 3, 'x': 2, 'y': 2})
   >>> c.update({'x': 1, 'z': -1})            # updating empty counter
   >>> c
       Counter({'x': 2, 'y': 2, 'z':2}


    This method is used to get the elements of counter

     >>> elements = list(c.elements())
            ['y', 'y', 'x', 'x', 'z', 'z', 'z']
    >>> set(elements)
          {'x', 'y', 'z'}


    This method is used to get the sequence of n most common elements and their respective counts.

    >>> collections.Counter('antidisestablishmentarianism')
           Counter({'i': 5, 'a': 4, 's': 4, 'n': 3, 't': 3, 'e': 2, 'm': 2, 'b': 1, 'd': 1, 'h': 1, 'l': 1, 'r': 1})
    >>> collections.Counter('antidisestablishmentarianism').most_common(3)
       [('i', 5), ('a', 4), ('s', 4)]

 we can also count the most_common lines in a file.

    >>> with open('filename', 'rb') as f:
        ...    line_count = Counter(f)
        ...    print line_count

Arithmetic Operations:

    >>> import collections
    >>> c1 = collections.Counter(['m', 'i', 'c', 'r', 'o', 'i', 'c', 'm', 'm'])
    >>> c2 = collections.Counter('micropyramid')
    >>> c1 + c2
         Counter({'m': 5, 'i': 4, 'c': 3, 'r': 3, 'o': 2, 'a': 1, 'd': 1, 'p': 1, 'y': 1})
    >>> c1 - c2
        Counter({'c': 1, 'm': 1})        # it will not show count zero elements
    >>> c1 & c2
        Counter({'i': 2, 'm': 2, 'c': 1, 'r': 1, 'o': 1})
    >>> c1 | c2
        Counter({'m': 3, 'c': 2, 'i': 2, 'r': 2, 'a': 1, 'd': 1, 'o': 1, 'p': 1, 'y': 1})

Working with OrderedDict:

        OrderedDict is the dictionary subclass which tracks the order of its contents in which they are added.

       The regular dictionary doesn't track the insertion order, rather it produces the values in an arbirary order.

    Regular Dictionary Example:

      >>> reg_dict = {}
      >>> reg_dict['x'] = 'X'
      >>> reg_dict['y'] = 'Y'
      >>> reg_dict['z'] = 'Z'
      >>> for k, v in reg_dict.items():
        ...     print k, v
     y Y
     x X
     z Z

      >>> reg_dict2 = {}
      >>> reg_dict2['Z'] = 'Z'
      >>> reg_dict2['y'] = 'Y'
      >>> reg_dict2['x'] = 'X'
      >>> reg_dict2 == reg_dict

 Ordered Dictionary Example:

      >>> ord_dict = {}
      >>> ord_dict['x'] = 'X'
      >>> ord_dict['y'] = 'Y'
      >>> ord_dict['z'] = 'Z'
      >>> for k, v in ord_dict.items():
        ...     print k, v
     x X
     y Y
     z Z

      >>> ord_dict2 = {}
      >>> ord_dict2['Z'] = 'Z'
      >>> ord_dict2['y'] = 'Y'
      >>> ord_dict2['x'] = 'X'
         >>> ord_dict2 == ord_dict

Sorting Dictionary by Key and Value:

   >>>  d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

   >>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))                       # sorting by Key 
          OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

   >>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))                       # sorting by Value
         OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

Working with defaultdict:

     defaultdict is a dictionary, unlike regular dictionary defaultdict is initialized with a function called default_factory() it takes no arguments and provides the default value for nonexistent key.

     So there is no chance to get KeyError while using defaultdict, perticulary when we deal with nested lists inside a dictionary.


  >>> dict = {}
  >>> dict['colours']['favourite'] = 'red'
       KeyError: 'colours'

    to solve this problem we should use defaultdict

    >>> import collections
    >>> tree = lambda: collections.defaultdict(tree)
    >>> dict = tree()
    >>> dict['colours']['favourite'] = 'red'

to access this using json.dumps     

>>> import json
   >>> json.dumps(dict)
      '{"colours": {"favourite": "red"}}'

Posted On 15 February 2016 By MicroPyramid

Need any Help in your Project?Let's Talk

Latest Comments
Which is the best Python framework for web development?

Python is a general-purpose programming language. We can use python for so many applications and including web applications. Which provides common backend fast reliable and …

Continue Reading...
Unit testing with selenium-python

Unit testing with selenium-python. Unit test case example to test the front-end

Continue Reading...
Tips to choose the best custom software development company

Choosing the best company for your software development needs is the most important step. This blog explains you tips to outsource custom software development services.

Continue Reading...
WSGI explanation with simple APP

The main goal of WSGI is to facilitate easy interconnection of servers and web frameworks/applications. WSGI defines a standerd API for web servers(uWSGI, Twisted, Gunicorn) …

Continue Reading...
Understanding self and __init__ method in python Class.

Understand self and __init__ method in python Class?
Before understanding the "self" and "__init__" methods in python class, it's very helpful if we have the idea …

Continue Reading...
List of python class special methods or magic methods

python class special methods or magic methods. magic methods allow us to override or add the default functionality of python objects. One of the biggest …

Continue Reading...
Building and Parsing XML Document using Python

Creating XML document with required elements, Then Parsing it using Python to generate a serialized form of its contents.

Continue Reading...
Working with python collections Counter

Python collections - Counter is to count the frequency of character, OrderedDict is to track the order of the contents in which they are added …

Continue Reading...
Python to Debian package: Simple, Easy and Fast

Packaging python script to debian follows strict instructions, using the following instructions, most of the steps can be skipped hence making it easy and fast.
If …

Continue Reading...
Customize and Embed Vimeo Videos using Python Requests.

Using python requests and vimeo endpoints it becomes very easy and simple to upload our videos and customize them.

Vimeo Access token:
1. Create an …

Continue Reading...
Sending SMS, MMS using Twilio.

A simple Tutorial on sending SMS and MMS in python using Twilio. In this tutorial you will learn how to send SMS, MMS and checking …

Continue Reading...
Working with python collections part 1

Python Collections - named tuple is to access by the names specified and deque is to append and pop the elements from both sides of …

Continue Reading...
Python Arrow To Show Human Friendly Time

Arrow is a python library and command-line tool to genrerate, manipulate dates, times, timestamps.
use of arrow:
With the use of arrow, we can also create, manipulate, …

Continue Reading...
Getting Started with the IPython Notebook

IPython is a set of tools developed to make it easier for the programmers to work with Python and data. IPython provides extensions to the …

Continue Reading...
Building Documentation with readthedocs

In this blog, I'm going to explain you how to write the Sphinx docs using reStructuredText to host in the Read the Docs.

Installing Sphinx

Continue Reading...
Create excel file, Insert image, Draw Bar Graphs in excel files in python using xlsxwriter

Xlsxwriter is a python module through which we can write data to Excel 2007+ XLSX file format. In this blog post we learn to write …

Continue Reading...
Integrate Twitter Social API into Django App

Integrating Twitter sign in (OAuth) in Django App, which includes
1. Capturing username via Twitter Login
2. Updating authenticated user current status on twitter(tweets).

Continue Reading...
How to implement Case Insensitive CSV DictReader in python

In general use cases we upload the CSV files to the system to store huge amount of data by uploading single file. For example in …

Continue Reading...
Python using yield and generators.

Generators are memory efficient. They allow us to code with minimum intermediate arguments, less data structures. Generators are of two types, generator expressions and generator …

Continue Reading...
Introduction to Object Oriented Programming with Python 3

Introduction to Object Oriented Programming with Python

Continue Reading...
Python Coding Techniques and Programming Practices

Coding techniques and programming practices are one of the features of a professional programmer. While writing code to solve a problem programmer should make simple …

Continue Reading...

Using Fabric, we can develop interactive script for ec2 region, ec2 flavour amazon web services. For this, you need aws account, security group, key pair, …

Continue Reading...
Generating PDF Files in Python using xhtml2pdf

There are many ways for generating PDF in python. In this post I will be presenting PDF files generation with xhtml2pdf.

xhtml2pdf: xhtml2pdf is a …

Continue Reading...
Using Python xlwt generating CSV writer and Excel files

In most of the cases, you need to export the data from your database to different formats. In this post I will show you how …

Continue Reading...
How to access development server publicly using Localtunnel

We do need to expose our local server to hit call-back URLs while programming with other APIs. There is a tool called local tunnel from …

Continue Reading...
How to generate PDF Files from HTML In Python using PDFKIT

There are many approches for generating PDF in python. pdfkit is one of the better approache as, it renders HTML into PDF with various image …

Continue Reading...
Converting Audio and Video files using FFMPEG Tool

FFMPEG is a command-line tool that converts audio or video to required formats, which handle multimedia data. It can also capture and encode in real-time.

Continue Reading...
Python Web Scraping with Beautiful soup

Download all One Piece animation series episodes by scraping site using BeautifulSoup python library.

Continue Reading...
Publishing Python Modules with PIP via PyPi

We'll install so many packages in our day to day python development. Now in this blog post, we'll try to know how to create our …

Continue Reading...
Programming with python: Decorators

Python decorators supports aspect-oriented programming. It is used to add or modify code in functions or classes. Using decorators will provide security, tracing, looking ..etc …

Continue Reading...
Vim for Python Web Development

Having a good environment setup is important for effective, fast and easy coding. We have different IDE's like eclipse, pycharm, sublime etc.. which are powerful …

Continue Reading...
Understanding Python Properties

Python Properties is a class for managing class attributes in Python. Property( ) is a built-in function that creates and returns a property object

attribute_name …

Continue Reading...
QRCode generation in python

A Quick Response code(QRCode) is a two-dimensional pictographic code used for its fast readability and comparatively large storage capacity. The code consists of black modules …

Continue Reading...
Understanding Audio Quality: Bit Rate, Sample Rate

Audio Quality is the accuracy and enjoyability of the audio which the user can listen from an electronic device. Audio quality depends upon the bit …

Continue Reading...
Programming with python Descriptors (_get_, _set_, _delete_) - MicroPyramid

Python descriptors are object attributes that are only invoked for new style of classes. Python descriptors comes under the category of meta programming(code that manipulates …

Continue Reading...
Debugging in Python

When something goes wrong with your code instead of using standard debugging techniques such as print statements use debugging tools. I found two great tools …

Continue Reading...
Python development environment on windows

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of …

Continue Reading...

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties