Collections



Overview



• In addition to the native data structures, Python also includes a collections module in the Standard Library

CollectionDescription
namedtuple()factory function for creating tuple subclasses with named fields
dequelist-like container with fast appends and pops on either end
ChainMapdict-like class for creating a single view of multiple mappings
Counterdict subclass for counting hashable objects
OrderedDictdict subclass that remembers the order entries were added
defaultdictdict subclass that calls a factory function to supply missing values
UserDictwrapper around dictionary objects for easier dict subclassing
UserListwrapper around list objects for easier list subclassing
UserStringwrapper around string objects for easier string subclassing


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

OrderedDict Collection



• Ordered Dictionaries work almost exactly like the native dict data structure, with one enhancement: they maintain the order of the items added to them
• Is not a native data structure, need to import

>>> from collections import OrderedDict

>>> od = OrderedDict()
>>> od["apples"] = 5
>>> od["pears"] = 2
>>> od["oranges"] = 9

>>> od["pears"]
2

>>> od["bananas"] = 12

>>> od
OrderedDict([('apples'5), ('pears'2), ('oranges'9), ('bananas'12)])


This OrderedDict worked just like the dict data structure with the following differences:
1. We did have to import it before we could use it
2. We added the key-value pairs to it incrementally, to demonstrate how it maintains the order in which they were added
3. When you look at the contents of the OrderedDict it looks a little different OrderedDict(<list of tuples>)


Index