Counter is very useful in counting occurrences of hashable objects. The elements are stored as dictionary keys and counts are stored as dictionary values.
Example:
To count the frequency of a character in a given string.
Initializing Counter:
We can initialize counter in three ways.
Creating and Updating Counters:
elements():
This method is used to get the elements of counter
most_common([n]):
This method is used to get the sequence of n most common elements and their respective counts.
we can also count the most_common lines in a file.
Arithmetic Operations:
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
True
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
False
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)])
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.
example:
to solve this problem we should use defaultdict
to access this using json.dumps
Micropyramid is a software development and cloud consulting partner for enterprise businesses across the world. We work on python, Django, Salesforce, Angular, Reactjs, React Native, MySQL, PostgreSQL, Docker, Linux, Ansible, git, amazon web services. We are Amazon and salesforce consulting partner with 5 years of cloud architect experience. We develop e-commerce, retail, banking, machine learning, CMS, CRM web and mobile applications.
Django-CRM :Customer relationship management based on Django
Django-blog-it : django blog with complete customization and ready to use with one click installer Edit
Django-webpacker : A django compressor tool
Django-MFA : Multi Factor Authentication
Docker-box : Web Interface to manage full blown docker containers and images
More...