2016-05-02 07:02:54 -04:00
|
|
|
:mod:`ucollections` -- collection and container types
|
2016-05-01 17:36:58 -04:00
|
|
|
=====================================================
|
|
|
|
|
2018-02-20 20:34:59 -05:00
|
|
|
.. include:: ../templates/unsupported_in_circuitpython.inc
|
|
|
|
|
2016-05-02 07:02:54 -04:00
|
|
|
.. module:: ucollections
|
2016-05-01 17:36:58 -04:00
|
|
|
:synopsis: collection and container types
|
|
|
|
|
2018-02-20 20:34:59 -05:00
|
|
|
|see_cpython_module| :mod:`cpython:collections`.
|
2017-07-02 08:37:31 -04:00
|
|
|
|
2016-05-01 17:36:58 -04:00
|
|
|
This module implements advanced collection and container types to
|
|
|
|
hold/accumulate various objects.
|
|
|
|
|
|
|
|
Classes
|
|
|
|
-------
|
|
|
|
|
|
|
|
.. function:: namedtuple(name, fields)
|
|
|
|
|
|
|
|
This is factory function to create a new namedtuple type with a specific
|
2016-07-31 19:52:00 -04:00
|
|
|
name and set of fields. A namedtuple is a subclass of tuple which allows
|
2016-05-01 17:36:58 -04:00
|
|
|
to access its fields not just by numeric index, but also with an attribute
|
|
|
|
access syntax using symbolic field names. Fields is a sequence of strings
|
2016-07-31 19:52:00 -04:00
|
|
|
specifying field names. For compatibility with CPython it can also be a
|
2016-05-01 17:36:58 -04:00
|
|
|
a string with space-separated field named (but this is less efficient).
|
|
|
|
Example of use::
|
|
|
|
|
2016-05-02 07:02:54 -04:00
|
|
|
from ucollections import namedtuple
|
2016-05-01 17:36:58 -04:00
|
|
|
|
|
|
|
MyTuple = namedtuple("MyTuple", ("id", "name"))
|
|
|
|
t1 = MyTuple(1, "foo")
|
|
|
|
t2 = MyTuple(2, "bar")
|
|
|
|
print(t1.name)
|
|
|
|
assert t2.name == t2[1]
|
|
|
|
|
|
|
|
.. function:: OrderedDict(...)
|
|
|
|
|
|
|
|
``dict`` type subclass which remembers and preserves the order of keys
|
|
|
|
added. When ordered dict is iterated over, keys/items are returned in
|
|
|
|
the order they were added::
|
|
|
|
|
2016-05-02 07:02:54 -04:00
|
|
|
from ucollections import OrderedDict
|
2016-05-01 17:36:58 -04:00
|
|
|
|
|
|
|
# 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
|