Collection in Python with examples

In python, collections are the containers used for storing the data. The built-in data structures in python are tuples, lists, sets and dictionaries. The collections class will provide additional data structures apart from the built-in data structures.

Some of the data structures in the ‘collections’ module −

  • Counter
  • Named tuple
  • ordered
  •  
    from collections import Counter
    a="tutorials point"
    result=Counter(a)
    print(result)

    OUTPUT:
    Counter({‘t’: 3, ‘o’: 2, ‘i’: 2, ‘u’: 1, ‘r’: 1, ‘a’: 1, ‘l’: 1, ‘s’: 1, ‘p’: 1, ‘n’: 1

  • default
  • Deque
  • Chain map
  • Counter

It is the type of collection in which the elements will be stored as dictionary keys and the counts will be stored as dictionary values.

Whenever you want to calculate the frequency of any item in a list, traditionally you would use a variable called ‘count’ which would be initially set to zero and will be incremented by one each time you encounter the item. This is not an optimized way when the list is long. Hence, to prevent this and to count different objects at the same time, we will make use of counters.

values() function

The values() function will give a list of the counts associated with all the values.

OUTPUT:
values([2, 3, 1])

from collections import Counter
a=["apple", "mango", "cherry", "apple", "mango" ,"mango"]
result=Counter(a)
print(result. values())

output:

values([2, 3, 1])

most_ common() function

The most_ common() function is used to give a dictionary of the item/items with the maximum count. The number of values that need to be displayed has to be mentioned inside the paranthesis

from collections import Counter
a=["apple", "mango", "cherry", "apple", "mango", "mango"]
result=Counter(a)
print(result. most common(1))
print(result. most_ common(2))
OUTPUT:

[(‘mango’, 3)] [(‘mango’, 3), (‘apple’, 2)]

named tuple() function

The named tuple() will allow us to create tuples with named fields. So, instead of accessing the items using the indices, we can access them using the dot notation.

Using the indices to access the items of a tuple can be difficult and confusing. To prevent that, we can make use of named tuple().

Just like tuples, named tuples are also immutable.

named tuple takes two arguments.

from collections import named tuple
person=named tuple("person",["name", "place", "sex", "age"])
id=person("kavya","Hyderabad","F","21")
print(id[1])
print(id[3])
print(id. place)
print(id. age)
output:

Hyderabad 21 Hyderabad 21

Ordered

Ordered  is a dictionary which can remember the order of its items. It is used for preserving the order in which the items will be added into the list. The items can be added to the Ordered in various ways similar to that of the ordinary dictionary.

from collections import Ordered
d=Ordered()
d['Ram']=100
d['Dhoni']=90
d['Rohit']=110
d['Kohli']=95
print(d)
from collections import Ordered
d=Ordered([('sachin',100),('Dhoni',90),('Rohit',110),('Kohli',95)])
print(d)
print(d. keys())

output:
Ordered([(‘Ram’, 100), (‘Dhoni’, 90), (‘Rohit’, 110), (‘Kohli’, 95)]) odict_keys([‘sachin’, ‘Dhoni’, ‘Rohit’, ‘Kohli’])

Default

The default has all the functionalities of a dictionary with the additional feature where it will never give a Key Error. In a dictionary, if you try to access or modify the keys that do not exist, you will get a Key Error. Whereas, default  always assigns a default value if the key does not exist. Hence, default is used for handling missing keys.

from collections import default d=default(int) d[‘Ram’]=90 d[‘Dhoni’]=80 d[‘Virat’]=95 print(d) print(d[‘Dhoni’]) print(d[‘Rohit’])

from collections import default
d=default(int)
d['Ram']=90
d['Dhoni']=80
d['Virat']=95
print(d)
print(d['Dhoni'])
print(d['Rohit'])
from collections import default
d=default(float)
d['Ram']=90
d['Dhoni']=80
print(d['Rohit'])
output:

default (<class 'int'="">, {'Ram': 90, 'Dhoni': 80, 'Virat': 95})
80
0
0.0

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top