AppDividend
Latest Code Tutorials

Python Collections Tutorial With Example | Python’s Collections Module

0

Python Collections Tutorial With Example | Python’s Collections Module is today’s topic. The collections module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers like a dictionary, listset, and tuple. In addition to the particular container classes, the collections module provides abstract base classes that can be used to test whether the class provides a specific interface, for example, whether it is hashable or a mapping.

Python Collections Tutorial With Example

Python collection is similar to a basket that you can add and remove items from. In some cases, they are the same types of elements, and in others, they are different types of items. It’s the storage construct that allows us to collect the items. Python collections module was introduced to improve the functionalities of built-in collection containers. Collections module was first introduced in 2.4 release of Python.

The collection will survive in memory. You don’t need to build the collection or create any scaffolding. All of that is provided for free. Just create a collection instance and start adding your items. When you’re ready, you can pull the items out by name or by index (position within the collection).

Collections Module in Python

See the following Python Collections.

  1. Counter
  2. defaultdict
  3. OrderedDict
  4. deque
  5. namedtuple()

Counter

The Counter collections allow us to keep the count of all the items which are inserted into a collection with the keys. The Counter is the dictionary subclass for counting the hashable objects. It is the unordered collection where items are stored as dictionary keys, and their counts are stored as the dictionary values. Counts collections are allowed to be any integer value, including zero or negative counts. The Counter class is similar to bags or multisets in the other languages.

See the following code example.

# app.py

from collections import Counter

aladdinChars = [
    ('Jasmine', 30),
    ('Aladdin', 32),
    ('Gennie', 50),
    ('Jaffar', 40)
]

count = Counter(name for name, actual in aladdinChars)
print(count)

See the following output.

Python Collections Tutorial With Example

 

This way, we can count the number of times the key appeared in the list.

Items are counted from the iterable or initialized from another mapping (or counter).

# app.py

from collections import Counter
c = Counter(apple=4, samsung=8)
print(c)

See the output.

Python Counter Collections

 

Default Dict

The default dict can contain the duplicate keys. The advantage of using the default dictionary is that we can collect elements which belong to the same key. It returns a new dictionary-like object.

The defaultdict is the subclass of the built-in dict class.

Defaultdict overrides one method and adds one writable instance.

The remaining functionality is the same as for a dict class. See the following code example.

# app.py

from collections import defaultdict

aladdinChars = [
    ('Jasmine', 30),
    ('Aladdin', 32),
    ('Gennie', 50),
    ('Jaffar', 40)
]

dict_chars = defaultdict(list)

for key, value in aladdinChars:
    dict_chars[key].append(value)

print(list(dict_chars.items()))

See the below output.

Default Dict Tutorial

 

Now, let’s repeat the Jasmine value one more time and see the output.

# app.py

from collections import defaultdict

aladdinChars = [
    ('Jasmine', 30),
    ('Jasmine', 30),
    ('Aladdin', 32),
    ('Gennie', 50),
    ('Jaffar', 40)
]

dict_chars = defaultdict(list)

for key, value in aladdinChars:
    dict_chars[key].append(value)

print(list(dict_chars.items()))

See the output below.

Default Dict

 

OrderedDict

With an OrderedDict, an order of insertion is maintained when the key and values are inserted into a dictionary. If we try to add a key again, this will overwrite the previous value for that key. Here is a sample program to demonstrate the usage of an OrderDict.

# app.py

from collections import OrderedDict

aladdinChars = OrderedDict([
    ('Jasmine', 30),
    ('Jasmine', 30),
    ('Aladdin', 32),
    ('Gennie', 50),
    ('Jaffar', 40)
])

for key, value in aladdinChars.items():
    print(key, value)

See the output below.

OrderedDict Tutorial

 

In the above example, you can see that Jasmin value is repeated one more time, still, in the output, it appears only one time. That means, it will remove the duplicate values and also you can see that it has given us the values in order. The output order was the same as the order of insertion.

Deque

A Deque is a double-ended queue which allows us to add and remove the items from both the ends. It enhances the capabilities of a stack or a queue. Deques are the generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). Deques support thread-safe, memory efficient appends, and pop from either side of the deque with approximately the same O(1) performance in the either direction.

See the following code example of Deque in Python.

# app.py

from collections import deque

webname = deque('AppDividend')
print('Deque       :', webname)
print('Queue Length:', len(webname))
print('Left part   :', webname[0])
print('Right part  :', webname[-1])

webname.remove('A')
print('remove(After removing A):', webname)

See the following output.

Deque Tutorial

 

So, the dequeuing of the items were done automatically. We can also add items in the Deque on a specific end.

namedtuple

Python Tuples are the immutable lists. What this means that the value cannot be given to the key which already exists in a tuple. We can convert that Tuple to the Named tuple by assigning the name to all values present in that tuple. It will give a lot more context to the data present as well. See the following code.

# app.py

from collections import namedtuple

Person = namedtuple('Employee', 'name age gender')
data = Person(name='Krunal', age=26, gender='M')
print(data)
print('Name of Employee: {0}'.format(data.name))

See the output below.

namedtuple

 

So, that is how we can access the properties of a named tuple with a name we provide. Also, remember that a key name cannot be any Python keywords.

Finally, Python Collections Tutorial With Example | Python’s Collections Module article is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.