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

Install Python3 and IDLE on Ubuntu 18.04

Python 3.6 should be installed on Ubuntu 18.04 LTS by default. Python 3.7 (still in beta) is also available in the official...
28/12/2020

Sending an Email in Python

Sending an Email is one of the most common tasks I need to do in the web applications and other projects I create. With...
28/12/2020

How to Calculate Matrices in Python Without NumPy

For many applications, you need mathematics. In Python there is the maths module which handles the basics such as rounding,...
29/12/2020
Bài Viết

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

Mua Proxy V6 Nuôi Facebook Spam Hiệu Quả Tại Onetcomvn
03/06/2024

Hướng dẫn cách sử dụng ProxyDroid để duyệt web ẩn danh
03/06/2024

Mua proxy Onet uy tín tại Onet.com.vn
03/06/2024

Thuê mua IPv4 giá rẻ, tốc độ nhanh, uy tín #1
28/05/2024

Thuê địa chỉ IPv4 IPv6 trọn gói ở đâu chất lượng, giá RẺ nhất?
27/05/2024