Item Sorted Dictionary Recipe¶
-
class
sortedcollections.
ItemSortedDict
(*args, **kwargs)¶ Sorted dictionary with key-function support for item pairs.
Requires key function callable specified as the first argument. The callable must accept two arguments, key and value, and return a value used to determine the sort order. For example:
def multiply(key, value): return key * value mapping = ItemSortedDict(multiply, [(3, 2), (4, 1), (2, 5)]) list(mapping) == [4, 3, 2]
Above, the key/value item pairs are ordered by
key * value
according to the callable given as the first argument.-
__copy__
()¶ Return shallow copy of the mapping.
-
__delitem__
(key)¶ del mapping[key]
-
__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.
-
__setitem__
(key, value)¶ mapping[key] = value
-
copy
()¶ Return shallow copy of the mapping.
-