Indexable Dictionary Recipe¶
-
class
sortedcollections.
IndexableDict
(*args, **kwargs)¶ Dictionary that supports numerical indexing.
Keys are numerically indexable using the
iloc
attribute. For example:>>> indexable_dict = IndexableDict.fromkeys('abcde') >>> indexable_dict.keys() ['b', 'd', 'e', 'c', 'a'] >>> indexable_dict.iloc[0] 'b' >>> indexable_dict.iloc[-2:] ['c', 'a']
The
iloc
attribute behaves as a sequence-view for the mapping.-
__init__
(*args, **kwargs)¶ SortedDict provides the same methods as a dict. Additionally, SortedDict efficiently maintains its keys in sorted order. Consequently, the keys method will return the keys in sorted order, the popitem method will remove the item with the highest key, etc.
An optional key argument defines a callable that, like the key argument to Python’s sorted function, extracts a comparison key from each dict key. If no function is specified, the default compares the dict keys directly. The key argument must be provided as a positional argument and must come before all other arguments.
An optional iterable argument provides an initial series of items to populate the SortedDict. Each item in the series must itself contain two items. The first is used as a key in the new dictionary, and the second as the key’s value. If a given key is seen more than once, the last value associated with it is retained in the new dictionary.
If keyword arguments are given, the keywords themselves with their associated values are added as items to the dictionary. If a key is specified both in the positional argument and as a keyword argument, the value associated with the keyword is retained in the dictionary. For example, these all return a dictionary equal to
{"one": 2, "two": 3}
:SortedDict(one=2, two=3)
SortedDict({'one': 2, 'two': 3})
SortedDict(zip(('one', 'two'), (2, 3)))
SortedDict([['two', 3], ['one', 2]])
The first example only works for keys that are valid Python identifiers; the others work with any valid keys.
-