Collections in Python

28/12/2020
Python collections are just containers which can contain data objects of various data-types inside them. Each collection type has their own features which we will look at in this lesson. Let’s study about these collections and their most used data-types.

Type of Collections

We will study following collections in Python in this lesson:

  • OrderedDict
  • defaultdict
  • counter
  • namedtuple
  • deque

OrderedDict

When order of insertion of the key and value matters for the program, we should make use of OrderedDict collection. Also, when the value for the same key is inserted, last value is overwritten with the new value. Let us take a look at a sample program:

from collections import OrderedDict

author = OrderedDict([
    (1, ‘David’),
    (2, ‘Shubham’),
    (3, ‘Swapnil Tirthakar’),
])

for num, name in author.items():
    print(num, name)

Here is what we get back with this command:

OrderDict collection in Python

defaultdict

Next collection in Python is defaultdict. This collection can contain duplicate keys. The main advantage of this collection is that we can collect values which belong to the identical keys. Let’s look at a program which demonstrates the same:

from collections import defaultdict

grade = [
    (‘Shubham’, ‘B’),
    (‘David’, "A"),
    (‘LinuxHint’, ‘B’),
    (‘LinuxHint’, ‘A’)
]

dict_grade = defaultdict(list)

for key, value in grade:
    dict_grade[key].append(value)

print(list(dict_grade.items()))

Let’s see the output for this command:

DefaultDict collection in Python

Here, the items related to same key LinuxHint were collected and shown in the output as together.

counter

The Counter collections allow us to count all the values which are present in the collection against the same key. Here is a program to show how the counter collection works:

from collections import Counter

marks_collect = [
    (‘Shubham’, 72),
    (‘David’, 99),
    (‘LinuxHint’, 91),
    (‘LinuxHint’, 100)
]

counted = Counter(name for name, marks in marks_collect)
print(counted)

Here is what we get back with this command:

Counter collection in Python

This provides a very easy way to count items in a Puython collection.

namedtuple

We can also have collection of items where values are assigned to a named key. This way, it is easy to access a value which is assigned to a name instead of an index. Let us look at an example:

import collections

Person = collections.namedtuple(‘Person’, ‘name age gender’)
oshima = Person(name=‘Oshima’, age=25, gender=‘F’)
print(oshima)

print(‘Name of Person: {0}’.format(oshima.name))

Let’s see the output for this command:

Named Tuple collection in Python

deque

As a final example, we can maintain a collection of items and remove characters form it as a deque process. Let us look at an example for the same:

import collections

person = collections.deque(‘Oshima’)
print(‘Deque :’, person)
print(‘Queue Length:’, len(person))
print(‘Left part :’, person[0])
print(‘Right part :’, person[1])

person.remove(‘m’)
print(‘remove(m):’, person)

Here is what we get back with this command:

Dequeue collection in Python

Conclusion

In this lesson, we looked at various collections used in Python and what each collection offers as a different capability.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

Top 10 Python IDE for Ubuntu

Python is one of the most widely used general purpose programming languages. Many of the popular websites or application...
28/12/2020

Collections in Python

Python collections are just containers which can contain data objects of various data-types inside them. Each collection...
28/12/2020

Python Seaborn Tutorial

In this lesson on Python Seaborn library, we will look at various aspects of this data visualisation library which we can...
29/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Dịch Vụ Xây Dựng Hệ Thống Peering Với Internet Exchange (IXP)
04/04/2025

Dịch Vụ Triển Khai VPN Site-to-Site & Remote Access
04/04/2025

Dịch Vụ Thiết Lập Hệ Thống Tường Lửa (Firewall)
04/04/2025

Dịch Vụ Triển Khai Hệ Thống Ảo Hóa & Cloud
04/04/2025

Dịch Vụ Triển Khai Hệ Thống Ceph
04/04/2025