ucollections – Container Data Types
This module implements a subset of the corresponding CPython module, as described below. For more information, see the original CPython documentation: collections
This module implements advanced collection and container types to hold/accumulate various objects.
Classes
- ucollections.deque(iterable, maxlen[, flags])
Deques (double-ended queues) are a list-like container that supports O(1) appends and pops from either side of the deque. New deques are created using the following arguments:
iterable must be an empty tuple, and the new deque is created empty.
maxlen must be specified and the deque is bounded to this maximum length. Once the deque is full, adding any new items will cause items to be dropped from the opposite end.
Optional flags can be 1 to check for overflow when adding items.
In addition to supporting
boolandlen, deque objects have the following methods:- deque.append(x)
Add x to the right side of the deque. If overflow checking is enabled and there is no remaining space, an IndexError will be raised.
- deque.popleft()
Remove and return an item from the left side of the deque. If no items are present, an IndexError will be raised.
- ucollections.namedtuple(name, fields)
This is a factory function for creating a new namedtuple type with a specific name and set of fields. A namedtuple is a subclass of tuple which allows accessing its fields not just by numeric index, but also with an attribute-access syntax using symbolic field names. Fields is a sequence of strings specifying field names. For compatibility with CPython it can also be a string with space-separated field names (but this is less efficient).
Usage example:
from ucollections import namedtuple MyTuple = namedtuple("MyTuple", ("id", "name")) t1 = MyTuple(1, "foo") t2 = MyTuple(2, "bar") print(t1.name) assert t2.name == t2[1]
- ucollections.OrderedDict(...)
dicttype subclass that remembers and preserves the order of keys added. When iterating over an OrderedDict, keys/items are returned in the order they were added:from ucollections import OrderedDict # To make benefit of ordered keys, OrderedDict should be initialized # from sequence of (key, value) pairs. d = OrderedDict([("z", 1), ("a", 2)]) # More items can be added as usual d["w"] = 5 d["b"] = 3 for k, v in d.items(): print(k, v)
Output:
z 1 a 2 w 5 b 3