|
| 1 | +:mod:`_collections` -- collection and container types |
| 2 | +===================================================== |
| 3 | + |
| 4 | +.. module:: _collections |
| 5 | + :synopsis: collection and container types |
| 6 | + |
| 7 | +This module implements advanced collection and container types to |
| 8 | +hold/accumulate various objects. |
| 9 | + |
| 10 | +Classes |
| 11 | +------- |
| 12 | + |
| 13 | +.. function:: namedtuple(name, fields) |
| 14 | + |
| 15 | + This is factory function to create a new namedtuple type with a specific |
| 16 | + name and set of fields. A namedtyple is a subclass of tuple which allows |
| 17 | + to access its fields not just by numeric index, but also with an attribute |
| 18 | + access syntax using symbolic field names. Fields is a sequence of strings |
| 19 | + specifying field names. For compatibily with CPython it can also be a |
| 20 | + a string with space-separated field named (but this is less efficient). |
| 21 | + Example of use:: |
| 22 | + |
| 23 | + from _collections import namedtuple |
| 24 | + |
| 25 | + MyTuple = namedtuple("MyTuple", ("id", "name")) |
| 26 | + t1 = MyTuple(1, "foo") |
| 27 | + t2 = MyTuple(2, "bar") |
| 28 | + print(t1.name) |
| 29 | + assert t2.name == t2[1] |
| 30 | + |
| 31 | +.. function:: OrderedDict(...) |
| 32 | + |
| 33 | + ``dict`` type subclass which remembers and preserves the order of keys |
| 34 | + added. When ordered dict is iterated over, keys/items are returned in |
| 35 | + the order they were added:: |
| 36 | + |
| 37 | + from _collections import OrderedDict |
| 38 | + |
| 39 | + # To make benefit of ordered keys, OrderedDict should be initialized |
| 40 | + # from sequence of (key, value) pairs. |
| 41 | + d = OrderedDict([("z", 1), ("a", 2)]) |
| 42 | + # More items can be added as usual |
| 43 | + d["w"] = 5 |
| 44 | + d["b"] = 3 |
| 45 | + for k, v in d.items(): |
| 46 | + print(k, v) |
| 47 | + |
| 48 | + Output:: |
| 49 | + |
| 50 | + z 1 |
| 51 | + a 2 |
| 52 | + w 5 |
| 53 | + b 3 |
0 commit comments