Back to module index

Go to module by name

collections (package)

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




Classes

ChainMap

 A ChainMap groups multiple dicts (or other mappings) together
    to create a single, updateable view.

    The underlying mappings are stored in a list.  That list is public and can
    be accessed or updated using the *maps* attribute.  There is no other
    state.

    Lookups search the underlying mappings successively until a key is found.
    In contrast, writes, updates, and deletions only operate on the first
    mapping.

    
clear(self)

  Clear maps[0], leaving maps[1:] intact.
copy(self)

  New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]
fromkeys(iterable, *args)

  Create a ChainMap with a single dict created from the iterable.
get(self, key, default=None)
items(self)

  D.items() -> a set-like object providing a view on D's items
keys(self)

  D.keys() -> a set-like object providing a view on D's keys
new_child(self, m=None, **kwargs)

  New ChainMap with a new map followed by all previous maps.
          If no map is provided, an empty dict is used.
          Keyword arguments update the map or new empty dict.
        
pop(self, key, *args)

  Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].
popitem(self)

  Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.
setdefault(self, key, default=None)

  D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
update(self, other=(), /, **kwds)

   D.update([E, ]**F) -> None.  Update D from mapping/iterable E and F.
              If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
              If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
              In either case, this is followed by: for k, v in F.items(): D[k] = v
        
values(self)

  D.values() -> an object providing a view on D's values
parents = <property object at 0x7f75e3bdc090>
  New ChainMap from maps[1:].

Counter

Dict subclass for counting hashable items.  Sometimes called a bag
    or multiset.  Elements are stored as dictionary keys and their counts
    are stored as dictionary values.

    >>> c = Counter('abcdeabcdabcaba')  # count elements from a string

    >>> c.most_common(3)                # three most common elements
    [('a', 5), ('b', 4), ('c', 3)]
    >>> sorted(c)                       # list all unique elements
    ['a', 'b', 'c', 'd', 'e']
    >>> ''.join(sorted(c.elements()))   # list elements with repetitions
    'aaaaabbbbcccdde'
    >>> sum(c.values())                 # total of all counts
    15

    >>> c['a']                          # count of letter 'a'
    5
    >>> for elem in 'shazam':           # update counts from an iterable
    ...     c[elem] += 1                # by adding 1 to each element's count
    >>> c['a']                          # now there are seven 'a'
    7
    >>> del c['b']                      # remove all 'b'
    >>> c['b']                          # now there are zero 'b'
    0

    >>> d = Counter('simsalabim')       # make another counter
    >>> c.update(d)                     # add in the second counter
    >>> c['a']                          # now there are nine 'a'
    9

    >>> c.clear()                       # empty the counter
    >>> c
    Counter()

    Note:  If a count is set to zero or reduced to zero, it will remain
    in the counter until the entry is deleted or the counter is cleared:

    >>> c = Counter('aaabbc')
    >>> c['b'] -= 2                     # reduce the count of 'b' by two
    >>> c.most_common()                 # 'b' is still in, but its count is zero
    [('a', 3), ('c', 1), ('b', 0)]

    
clear(...)

  D.clear() -> None.  Remove all items from D.
copy(self)

  Return a shallow copy.
elements(self)

  Iterator over elements repeating each as many times as its count.

          >>> c = Counter('ABCABC')
          >>> sorted(c.elements())
          ['A', 'A', 'B', 'B', 'C', 'C']

          # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
          >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
          >>> product = 1
          >>> for factor in prime_factors.elements():     # loop over factors
          ...     product *= factor                       # and multiply them
          >>> product
          1836

          Note, if an element's count has been set to zero or is a negative
          number, elements() will ignore it.

        
fromkeys(iterable, v=None)
get(self, key, default=None, /)

  Return the value for key if key is in the dictionary, else default.
items(...)

  D.items() -> a set-like object providing a view on D's items
keys(...)

  D.keys() -> a set-like object providing a view on D's keys
most_common(self, n=None)

  List the n most common elements and their counts from the most
          common to the least.  If n is None, then list all element counts.

          >>> Counter('abracadabra').most_common(3)
          [('a', 5), ('b', 2), ('r', 2)]

        
pop(...)

  D.pop(k[,d]) -> v, remove specified key and return the corresponding value.

  If the key is not found, return the default if given; otherwise,
  raise a KeyError.
popitem(self, /)

  Remove and return a (key, value) pair as a 2-tuple.

  Pairs are returned in LIFO (last-in, first-out) order.
  Raises KeyError if the dict is empty.
setdefault(self, key, default=None, /)

  Insert key with a value of default if key is not in the dictionary.

  Return the value for key if key is in the dictionary, else default.
subtract(self, iterable=None, /, **kwds)

  Like dict.update() but subtracts counts instead of replacing them.
          Counts can be reduced below zero.  Both the inputs and outputs are
          allowed to contain zero and negative counts.

          Source can be an iterable, a dictionary, or another Counter instance.

          >>> c = Counter('which')
          >>> c.subtract('witch')             # subtract elements from another iterable
          >>> c.subtract(Counter('watch'))    # subtract elements from another counter
          >>> c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch
          0
          >>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
          -1

        
total(self)

  Sum of the counts
update(self, iterable=None, /, **kwds)

  Like dict.update() but add counts instead of replacing them.

          Source can be an iterable, a dictionary, or another Counter instance.

          >>> c = Counter('which')
          >>> c.update('witch')           # add elements from another iterable
          >>> d = Counter('watch')
          >>> c.update(d)                 # add elements from another counter
          >>> c['h']                      # four 'h' in which, witch, and watch
          4

        
values(...)

  D.values() -> an object providing a view on D's values

OrderedDict

Dictionary that remembers insertion order
clear(...)

  od.clear() -> None.  Remove all items from od.
copy(...)

  od.copy() -> a shallow copy of od
fromkeys(iterable, value=None)

  Create a new ordered dictionary with keys from iterable and values set to value.
get(self, key, default=None, /)

  Return the value for key if key is in the dictionary, else default.
items(...)
keys(...)
move_to_end(self, /, key, last=True)

  Move an existing element to the end (or beginning if last is false).

  Raise KeyError if the element does not exist.
pop(...)

  od.pop(key[,default]) -> v, remove specified key and return the corresponding value.

  If the key is not found, return the default if given; otherwise,
  raise a KeyError.
popitem(self, /, last=True)

  Remove and return a (key, value) pair from the dictionary.

  Pairs are returned in LIFO order if last is true or FIFO order if false.
setdefault(self, /, key, default=None)

  Insert key with a value of default if key is not in the dictionary.

  Return the value for key if key is in the dictionary, else default.
update(...)
values(...)

UserDict

clear(self)

  D.clear() -> None.  Remove all items from D.
copy(self)
fromkeys(iterable, value=None)
get(self, key, default=None)

  D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
items(self)

  D.items() -> a set-like object providing a view on D's items
keys(self)

  D.keys() -> a set-like object providing a view on D's keys
pop(self, key, default=<object object at 0x7f75e3c94190>)

  D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
            If key is not found, d is returned if given, otherwise KeyError is raised.
        
popitem(self)

  D.popitem() -> (k, v), remove and return some (key, value) pair
             as a 2-tuple; but raise KeyError if D is empty.
        
setdefault(self, key, default=None)

  D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
update(self, other=(), /, **kwds)

   D.update([E, ]**F) -> None.  Update D from mapping/iterable E and F.
              If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
              If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
              In either case, this is followed by: for k, v in F.items(): D[k] = v
        
values(self)

  D.values() -> an object providing a view on D's values

UserList

A more or less complete user-defined wrapper around list objects.
append(self, item)
clear(self)
copy(self)
count(self, item)
extend(self, other)
index(self, item, *args)
insert(self, i, item)
pop(self, i=-1)
remove(self, item)
reverse(self)
sort(self, /, *args, **kwds)

UserString

capitalize(self)
casefold(self)
center(self, width, *args)
count(self, sub, start=0, end=9223372036854775807)
encode(self, encoding='utf-8', errors='strict')
endswith(self, suffix, start=0, end=9223372036854775807)
expandtabs(self, tabsize=8)
find(self, sub, start=0, end=9223372036854775807)
format(self, /, *args, **kwds)
format_map(self, mapping)
index(self, sub, start=0, end=9223372036854775807)
isalnum(self)
isalpha(self)
isascii(self)
isdecimal(self)
isdigit(self)
isidentifier(self)
islower(self)
isnumeric(self)
isprintable(self)
isspace(self)
istitle(self)
isupper(self)
join(self, seq)
ljust(self, width, *args)
lower(self)
lstrip(self, chars=None)
maketrans(...)

  Return a translation table usable for str.translate().

  If there is only one argument, it must be a dictionary mapping Unicode
  ordinals (integers) or characters to Unicode ordinals, strings or None.
  Character keys will be then converted to ordinals.
  If there are two arguments, they must be strings of equal length, and
  in the resulting dictionary, each character in x will be mapped to the
  character at the same position in y. If there is a third argument, it
  must be a string, whose characters will be mapped to None in the result.
partition(self, sep)
removeprefix(self, prefix, /)
removesuffix(self, suffix, /)
replace(self, old, new, maxsplit=-1)
rfind(self, sub, start=0, end=9223372036854775807)
rindex(self, sub, start=0, end=9223372036854775807)
rjust(self, width, *args)
rpartition(self, sep)
rsplit(self, sep=None, maxsplit=-1)
rstrip(self, chars=None)
split(self, sep=None, maxsplit=-1)
splitlines(self, keepends=False)
startswith(self, prefix, start=0, end=9223372036854775807)
strip(self, chars=None)
swapcase(self)
title(self)
translate(self, *args)
upper(self)
zfill(self, width)

defaultdict

defaultdict(default_factory=None, /, [...]) --> dict with default factory

The default factory is called without arguments to produce
a new value when a key is not present, in __getitem__ only.
A defaultdict compares equal to a dict with the same items.
All remaining arguments are treated the same as if they were
passed to the dict constructor, including keyword arguments.

clear(...)

  D.clear() -> None.  Remove all items from D.
copy(...)

  D.copy() -> a shallow copy of D.
fromkeys(iterable, value=None, /)

  Create a new dictionary with keys from iterable and values set to value.
get(self, key, default=None, /)

  Return the value for key if key is in the dictionary, else default.
items(...)

  D.items() -> a set-like object providing a view on D's items
keys(...)

  D.keys() -> a set-like object providing a view on D's keys
pop(...)

  D.pop(k[,d]) -> v, remove specified key and return the corresponding value.

  If the key is not found, return the default if given; otherwise,
  raise a KeyError.
popitem(self, /)

  Remove and return a (key, value) pair as a 2-tuple.

  Pairs are returned in LIFO (last-in, first-out) order.
  Raises KeyError if the dict is empty.
setdefault(self, key, default=None, /)

  Insert key with a value of default if key is not in the dictionary.

  Return the value for key if key is in the dictionary, else default.
update(...)

  D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
  If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
  If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
  In either case, this is followed by: for k in F:  D[k] = F[k]
values(...)

  D.values() -> an object providing a view on D's values
default_factory = <member 'default_factory' of 'collections.defaultdict' objects>
  Factory for default value called by __missing__().

deque

deque([iterable[, maxlen]]) --> deque object

A list-like sequence optimized for data accesses near its endpoints.
append(...)

  Add an element to the right side of the deque.
appendleft(...)

  Add an element to the left side of the deque.
clear(...)

  Remove all elements from the deque.
copy(...)

  Return a shallow copy of a deque.
count(...)

  D.count(value) -> integer -- return number of occurrences of value
extend(...)

  Extend the right side of the deque with elements from the iterable
extendleft(...)

  Extend the left side of the deque with elements from the iterable
index(...)

  D.index(value, [start, [stop]]) -> integer -- return first index of value.
  Raises ValueError if the value is not present.
insert(...)

  D.insert(index, object) -- insert object before index
pop(...)

  Remove and return the rightmost element.
popleft(...)

  Remove and return the leftmost element.
remove(...)

  D.remove(value) -- remove first occurrence of value.
reverse(...)

  D.reverse() -- reverse *IN PLACE*
rotate(...)

  Rotate the deque n steps to the right (default n=1).  If n is negative, rotates left.
maxlen = <attribute 'maxlen' of 'collections.deque' objects>
  maximum size of a deque or None if unbounded

Functions

namedtuple

namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)

  Returns a new subclass of tuple with named fields.

      >>> Point = namedtuple('Point', ['x', 'y'])
      >>> Point.__doc__                   # docstring for the new class
      'Point(x, y)'
      >>> p = Point(11, y=22)             # instantiate with positional args or keywords
      >>> p[0] + p[1]                     # indexable like a plain tuple
      33
      >>> x, y = p                        # unpack like a regular tuple
      >>> x, y
      (11, 22)
      >>> p.x + p.y                       # fields also accessible by name
      33
      >>> d = p._asdict()                 # convert to a dictionary
      >>> d['x']
      11
      >>> Point(**d)                      # convert from a dictionary
      Point(x=11, y=22)
      >>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
      Point(x=100, y=22)

    

Modules

abc