The Python class Counter
is used to count elements in a container. It is a subclass of the dictionary class (Dictionary)) dict
which, in combination with different methods, has many possible uses. Discover them in the rest of this article.
What is Python Counter
?
Python Counter
is a useful tool that allows you to have different elements in a list and display the frequency of appearance of these elements. It is a subclass of Dictionary, the data structure implemented by the class dict
. While this task can easily be carried out manually for a short succession of values, it is much more complicated for long data sets. Python Counter
is an object that begins with an initial zero value. A single counter indicates the frequency of a particular object. If you want to follow the frequency of several different objects, use a separate meter for each object.
The class Counter
Can be used for lists, python tules, dictionaries and python thongs. Its syntax is as follows:
In the following paragraphs, we show you using a few simple examples how to use Python Counter
.
Web accommodation
Flexible, efficient and safe web accommodation
- SSL certificate and DDOS protection
- Data backup and restoration
- Assistance 24/7 and personal advisor
Python Counter
with a list
In the first example, we create a simple list with different values. This looks like this:
list = ['a', 'a', 'b', 'a', 'c', 'b', 'b', 'c', 'a', 'c', 'b', 'c']
python
The list has three different elements: 'a'
,, 'b'
And 'c'
. To find out how many of these elements are contained, we apply Python Counter
. The exit would then look like this:
Counter({'c' : 5, 'a' : 4, 'b' : 4})
python
To use Python Counter
you must first import the class. The result is displayed with print
. The complete code for this example would then be this:
from collections import Counter
list = ['a', 'a', 'b', 'a', 'c', 'b', 'b', 'c', 'a', 'c', 'b', 'c', 'c']
counter_list = Counter(list)
print(Counter(list))
python
The resulting output looks like this:
Counter({'c' : 5, 'a' : 4, 'b' : 4})
python
Python Counter
with a tuple
In the second example, we proceed very similarly. This time, Python Counter
must be applied to a tuple. Tuples are used in python to Store several values in a variable. As this is an ordered grouping of objects, the order is taken into account. The objects are placed in parentheses and separated by commas. Consequently, the code is in the following form:
from collections import Counter
tuple = ('a', 'a', 'b', 'a', 'c', 'b', 'b', 'c', 'a', 'c', 'b', 'c', 'c')
print(Counter(tuple))
python
The output is identical to the previous example:
Counter({'c' : 5, 'a' : 4, 'b' : 4})
python
Use in a dictionary
In a dictionary, the elements are stored in the form of key-value pairs and placed between accolades. If you use Python's Counter with a Dictionary, the latter is transformed into a Hashtable object. The keys to the original dictionary become the elements, and their values become their frequencies. For our example above, it might look like this:
from collections import Counter
dictionary = {'a' : 4, 'b' : 4, 'c' : 5}
counter_dictionary = Counter(dictionary)
print(Counter(dictionary))
python
The outing is then this one:
Counter({'c' : 5, 'a' : 4, 'b' : 4})
python
Advice
Reach your only three -step goal: with Deploy Now from Ionos, you easily connect your deposit, take advantage of the automatic configuration of the workflow and then access a reliable infrastructure. Take advantage of our suitable prices and our expertise.
Python Counter
In combination with a simple character string
You can get an idea of saving time and simplification of the work that Python can offer Counter
by applying this class to a character string (string in English). A character string is a Character continuation marked by quotes. The spaces are also taken into account. We choose the following character string for our example:
from collections import Counter
string = "This is an example"
counter_string = Counter(string)
print(Counter(string))
python
Now each character is counted as a sub-chain. The exit could therefore look like this:
Counter({' ' : 3, 'i' : 2, 's' : 2, 'T' : 1, 'h' : 1, 'a' : 1, 'n' : 1, 'e' : 1, 'x' : 1, 'm' : 1, 'p' : 1, 'l' : 1})
python
Extensions with .update()
Python offers many options for Counter
. For example, it is also possible to extend an existing counting using .update()
. To do this, we first create a simple code based on the principle mentioned above, but this time, we are not isolating the character strings separately:
from collections import Counter
Counter("blue")
print(Counter(string))
python
Our outing is then this:
Counter({'b' : 1, 'l' : 1, 'u' : 1, 'e' : 1})
python
If we apply now .update()
the code looks like this:
from collections import Counter
colors = Counter({'b' : 1, 'l' : 1, 'a' : 1, 'u' : 1})
colors.update("gray")
print(colors)
python
This also allows us to obtain an updated outing:
Counter({'b' : 1, 'l' : 1, 'u' : 1, 'e' : 1, 'g' : 1, 'r' : 1, 'a' : 1, 'y' : 1})
python
Access the values of Python Counter
You have the possibility of accessing the values of Python Counter
because this class works in a similar way to Dictionary. In the following code example, we show you some variations and the corresponding outputs. Here, the letters (letters) work like keys (keys) and the frequencies of counted elements (courses) as values (values).
from collections import Counter
letters = Counter("roof")
letters["o"]
2
letters["f"]
1
python
for letter in letters:
print(letter, letters[letter])
r 1
o 2
f 1
python
Here is what an example would look like with the method .keys()
::
for letter in letters.keys():
print(letter, letters[letter])
r 1
o 2
f 1
python
This is an example with .values()
::
for count in letters.values():
print(count)
1
2
1
python
This is the method .items()
::
for letter, count in letters.items():
print(letter, count)
r 1
o 2
f 1
python
Delete class elements
If you want to delete a python element Counter
use del
::
from collections import Counter
example = {'b' : 1, 'l' : 1, 'u' : 1, 'e' : 1}
del example["b"]
print(Counter(example))
python
Your new outing then presents itself as follows:
Counter({'l' : 1, 'u' : 1, 'e' : 1})
python
Determine the greatest accumulation with most_common(n)
With most_common(n)
for python Counter
you can determine which elements are the most and the least often represented. Take an example: a product is listed in different colors. Next to the colors is indicated the frequency to which the product is still in stock in the corresponding variant. A negative value means that there is no longer an article corresponding in stock, but that this variant has still been pre -ordered. If we want to check which variant has the most articles, we use this code:
from collections import Counter
color_variations = Counter({'blue' : 2, 'gray' : -1, 'black' : 0})
most_articles = color_variations.most_common(1)
print(most_articles)
python
The outing is then this:
We can also display the smallest number of items. For this, we modify the code as follows:
from collections import Counter
color_variations = Counter({'blue' : 2, 'gray' : -1, 'black' : 0})
fewest_items = color_variations.most_common ()[:-2:-1]
print(fewest_items)
python
The corresponding output:
Arithmetic calculation with Python Counter
THE Arithmetic calculations are also possible with the help of Python Counter
. However, it is important to note that only positive values are displayed. We try some types of calculation.
A simple addition:
from collections import Counter
x = Counter(a=4, b=2, c=1)
y = Counter(a=2, b=1, c=2)
z = x + y
print(z)
python
Counter({'a' : 6, 'b' : 3, 'c' : 3})
python
Here's what subtraction looks like:
from collections import Counter
x = Counter(a=4, b=2, c=1)
y = Counter(a=2, b=1, c=2)
z = x - y
print(z)
python
Counter({'a' : 2, 'b' : 1})
python
As the value of 'c'
would now be negative, it is not displayed.
Sort data types by frequency
Another option that class offers you is a Data type listing in a file. For example, imagine a folder called « images » which contains many different files with different types of data. For an enumeration, we use the following code:
import pathlib
from collections import Counter
folder_path = pathlib.Path("Images/")
extensions = [entry.suffix for entry in folder_path.iterdir() if entry.is_file()]]
extension_counter = Counter(extensions)
print(extension_counter)
python
Exclude negative and zero values
To eliminate zero or negative values with Python Counter
use this code:
from collections import Counter
valeurs = Counter(a=6, b=0, c=1, d=-4)
valeur = +values
print(values)
python
The corresponding output is then this:
Counter({'a' : 6, 'c' : 1})
python