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.
We can initialize counter in three ways.
Creating and Updating Counters:
This method is used to get the elements of counter
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.
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:
Ordered Dictionary Example:
Sorting Dictionary by Key and Value:
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.
to solve this problem we should use defaultdict
to access this using json.dumps