Python counter to dict

Python Counter in Collections with Example

Python Counter is a container that will hold the count of each of the elements present in the container. The counter is a sub-class available inside the dictionary class.

The counter is a sub-class available inside the dictionary class. Using the Python Counter tool, you can count the key-value pairs in an object, also called a hash table object.

Why use Python Counter?

Here, are major reasons for using Python 3 Counter:

  • The Counter holds the data in an unordered collection, just like hashtable objects. The elements here represent the keys and the count as values.
  • It allows you to count the items in an iterable list.
  • Arithmetic operations like addition, subtraction, intersection, and union can be easily performed on a Counter.
  • A Counter can also count elements from another counter

Introduction to Python Counter

Python Counter takes in input a list, tuple, dictionary, string, which are all iterable objects, and it will give you output that will have the count of each element.

Читайте также:  Arraylist linkedlist list java

Consider you have a following list :

The list has elements x , y and z.When you use Counter on this list , it will count how many times x , y and z is present. The output if counter is used on list1 should be something like :

So we have the count of x as 4, y as 2 and z as 2.

To make use of Counter we need to import it first as shown in the below given example:

from collections import Counter

Here is a simple example , that shows the working of Counter module.

from collections import Counter list1 = ['x','y','z','x','x','x','y', 'z'] print(Counter(list1))

Counter with String

In Python, everything is an object and string is an object too. Python string can be created simply by enclosing characters in the double quote. Python does not support a character type. These are treated as strings of length one, also considered as a substring.

In the example below, a string is passed to Counter. It returns dictionary format, with key/value pair where the key is the element and value is the count. It also considers space as an element and gives the count of spaces in the string.

from collections import Counter my_str = "Welcome to Guru99 Tutorials!" print(Counter(my_str))

Counter with List

A list is an iterable object that has its elements inside square brackets.

The elements in the list when given to the Counter will be converted to a hashtable objects wherein the elements will become keys and the values will be the count of the elements from the list given.

For example [‘x’,’y’,’z’,’x’,’x’,’x’,’y’,’z’]. Once you give the list the Counter, it will give you the count of each element in the list.

from collections import Counter list1 = ['x','y','z','x','x','x','y','z'] print(Counter(list1))

Counter with Dictionary

A dictionary has elements as key/value pair, and they are written inside curly brackets.

Once the dictionary is given to the Counter, it will be converted to a hashtable objects wherein the elements will become keys, and the values will be the count of the elements from the dictionary given.

For example : . The Counter function will try to find the count of each of the key in the given dictionary.

from collections import Counter dict1 = print(Counter(dict1))

Counter with Tuple

Tuple is a collection of objects separated by commas inside round brackets. Counter will give you the count of each of the elements in the tuple given.

Once the tuple is given to the Counter, it will be converted to a hashtable object wherein the elements will become keys and the values will be the count of the elements from the tuple given.

from collections import Counter tuple1 = ('x','y','z','x','x','x','y','z') print(Counter(tuple1))

Accessing, Initializing and Updating Counters

Initializing Counter

A Counter can be initialized by passing string value, list, dictionary, or tuple as shown below:

from collections import Counter print(Counter("Welcome to Guru99 Tutorials!")) #using string print(Counter(['x','y','z','x','x','x','y', 'z'])) #using list print(Counter()) #using dictionary print(Counter(('x','y','z','x','x','x','y', 'z'))) #using tuple

You can also initialize a empty Counter as shown below:

from collections import Counter _count = Counter()

Updating Counter

You can add values to the Counter by using update() method.

_count.update('Welcome to Guru99 Tutorials!')
from collections import Counter _count = Counter() _count.update('Welcome to Guru99 Tutorials!') print(_count)

Accessing Counter

To get the values from the Counter, you can do as follows:

from collections import Counter _count = Counter() _count.update('Welcome to Guru99 Tutorials!') print('%s : %d' % ('u', _count['u'])) print('\n') for char in 'Guru': print('%s : %d' % (char, _count[char]))

Deleting an Element from Counter

To delete an element from Counter you can make use of del , as shown in the example below:

from collections import Counter dict1 = del dict1["x"] print(Counter(dict1))

Arithmetic operation on Python Counter

Arithmetic operation like addition, subtraction, intersection and union can be done on a Counter as shown in the example below:

from collections import Counter counter1 = Counter() counter2 = Counter() #Addition counter3 = counter1 + counter2 # only the values that are positive will be returned. print(counter3) #Subtraction counter4 = counter1 - counter2 # all -ve numbers are excluded.For example z will be z = -2-4=-6, since it is -ve value it is not shown in the output print(counter4) #Intersection counter5 = counter1 & counter2 # it will give all common positive minimum values from counter1 and counter2 print(counter5) #Union counter6 = counter1 | counter2 # it will give positive max values from counter1 and counter2 print(counter6)
Counter() Counter() Counter() Counter()

Methods Available on Python Counter

There are some important methods available with Counter, here is the list of same:

  • elements() : This method will return you all the elements with count >0. Elements with 0 or -1 count will not be returned.
  • most_common(value): This method will return you the most common elements from Counter list.
  • subtract(): This method is used to deduct the elements from another Counter.
  • update(): This method is used to update the elements from another Counter.

Example : elements()

from collections import Counter counter1 = Counter() _elements = counter1.elements() # will give you all elements with positive value and count>0 for a in _elements: print(a)

Example: most_common(value)

from collections import Counter counter1 = Counter() common_element = counter1.most_common(2) # The dictionary will be sorted as per the most common element first followed by next. print(common_element) common_element1 = counter1.most_common() # if the value is not given to most_common , it will sort the dictionary and give the most common elements from the start.The last element will be the least common element. print(common_element1)
[('y', 12), ('x', 5)] [('y', 12), ('x', 5), ('x1', 0), ('z', -2)]

Example: subtract()

from collections import Counter counter1 = Counter() counter2 = Counter() counter1.subtract(counter2) print(counter1)

Example: update()

from collections import Counter counter1 = Counter() counter2 = Counter() counter1.update(counter2) print(counter1)

Reassigning Counts in Python

You can re-assign counts of Counter as shown below:

Consider you have a dictionary as :

You can change the count of the element as shown below:

from collections import Counter counter1 = Counter() counter1['y'] = 20 print(counter1)

Output: After executing you will see that y count is changed from 12 to 20

Get and set the count of Elements using Counter

To get the count of an element using Counter you can do as follows:

from collections import Counter counter1 = Counter() print(counter1['y']) # this will give you the count of element 'y'

To set the count of the element you can do as follows:

from collections import Counter counter1 = Counter() print(counter1['y']) counter1['y'] = 20 counter1['y1'] = 10 print(counter1)

Summary

  • Counter is a container that will hold the count of each of the elements present in the container.
  • Counter is a sub-class available inside the dictionary class.
  • Using the Python Counter tool, you can count the key-value pairs in an object, also called a hashtable object.
  • The Counter holds the data in an unordered collection, just like hashtable objects. The elements here represent the keys and the count as values.
  • It allows you to count the items in an iterable list.
  • Arithmetic operations like addition, subtraction, intersection, and union can be easily performed on a Counter.
  • A Counter can also count elements from another counter.
  • The important methods available on a Counter are elements() , most_common(value), subtract() and update().
  • A counter can be used on a string, list, dictionary, and tuple.

Источник

How to convert counter object to dict in Python?

The Counter object in Python is a subclass of dict and is used to count the occurrences of elements in a list. It provides a convenient way to keep track of the count of elements. However, sometimes it is necessary to convert the Counter object back to a normal dictionary, and this is where people encounter a problem. In this article, we will discuss two methods to convert a Counter object to a dictionary in Python.

Method 1: Using dict()

To convert a Counter object to a dictionary using dict(), you can simply pass the Counter object as an argument to the dict() function. This will create a new dictionary with the keys and values from the Counter object.

from collections import Counter c = Counter(a=3, b=2, c=1) d = dict(c) print(d)

In this example, we first create a Counter object with three keys (‘a’, ‘b’, ‘c’) and their respective counts. We then use the dict() function to convert the Counter object to a dictionary, which is stored in the variable d. Finally, we print the resulting dictionary.

from collections import Counter c = Counter('hello world') d = dict(c) print(d)

In this example, we create a Counter object from a string (‘hello world’). The resulting Counter object counts the occurrence of each character in the string. We then use the dict() function to convert the Counter object to a dictionary, which is stored in the variable d. Finally, we print the resulting dictionary.

In summary, to convert a Counter object to a dictionary using dict(), simply pass the Counter object as an argument to the dict() function. This will create a new dictionary with the keys and values from the Counter object.

Method 2: Using Counter.items()

To convert a Counter object to a dictionary in Python, you can use the items() method of the Counter object. This method returns a list of tuple pairs containing the keys and their corresponding counts. You can then convert this list of tuples to a dictionary using the dict() function.

from collections import Counter c = Counter('hello world') d = dict(c.items()) print(d)

In this example, we first create a Counter object c from the string ‘hello world’. We then convert c to a dictionary d using the items() method and the dict() function. Finally, we print the resulting dictionary d .

You can also use a dictionary comprehension to achieve the same result:

This creates a new dictionary d by iterating over the key-value pairs returned by the items() method of the Counter object c .

If you want to convert a Counter object to a dictionary of lists (where each key maps to a list of its counts), you can use a defaultdict:

from collections import defaultdict c = Counter('hello world') d = defaultdict(list) for k, v in c.items(): d[k].append(v) print(dict(d))

In this example, we first create a Counter object c from the string ‘hello world’. We then create a defaultdict d with the list factory function, which will create a new empty list for each new key encountered. We then iterate over the key-value pairs returned by the items() method of the Counter object c , appending each count to the list associated with its corresponding key in the defaultdict . Finally, we convert the defaultdict to a regular dictionary using the dict() function and print the resulting dictionary.

Источник

Оцените статью