4. Collections

It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.

Name

Description

namedtuple()

factory function for creating tuple subclasses with named fields

deque

list-like container with fast appends and pops on either end

ChainMap

dict-like class for creating a single view of multiple mappings

Counter

dict subclass for counting hashable objects

OrderedDict

dict subclass that remembers the order entries were added

defaultdict

dict subclass that calls a factory function to supply missing values

UserDict

wrapper around dictionary objects for easier dict subclassing

UserList

wrapper around list objects for easier list subclassing

UserString

wrapper around string objects for easier string subclassing

jose = {'first_name': 'José', 'last_name': 'Jiménez', 'agency': 'NASA'}

print(jose)
# {'first_name': 'José', 'last_name': 'Jiménez', 'agency': 'NASA'}

print(jose['first_name'], jose['last_name'], jose['agency'])
# José Jiménez NASA

4.1. OrderedDict

from collections import OrderedDict

jose = OrderedDict(first_name='José', last_name='Jiménez', agency='NASA')
print(jose)
# OrderedDict([('first_name', 'José'), ('last_name', 'Jiménez'), ('agency', 'NASA')])

4.2. namedtuple

from collections import namedtuple

Astronaut = namedtuple('Astronaut', ['first_name', 'last_name', 'agency'])
jose = Astronaut(first_name='José', last_name='Jiménez', agency='NASA')

print(jose)
# Astronaut(first_name='José', last_name='Jiménez', agency='NASA')

print(jose.first_name, jose.last_name, jose.agency)
# José Jiménez NASA

4.3. collections.Counter

import random


random_numbers = [random.randint(0, 10) for a in range(0, 50)]
counter = dict()

for number in random_numbers:
    if number in counter:
        counter[number] += 1
    else:
        counter[number] = 1

counter.items()
# [(7, 12), (4, 8), (9, 6), (1, 5), (2, 4)]
import random
from collections import Counter


random_numbers = [random.randint(0, 10) for a in range(0, 50)]
counter = Counter(random_numbers)

counter.most_common(5)
# [(7, 12), (4, 8), (9, 6), (1, 5), (2, 4)]