Value Sorted Dictionary Recipe

class sortedcollections.ValueSortedDict(*args, **kwargs)[source]

Sorted dictionary that maintains (key, value) item pairs sorted by value.

  • ValueSortedDict() -> new empty dictionary.

  • ValueSortedDict(mapping) -> new dictionary initialized from a mapping object’s (key, value) pairs.

  • ValueSortedDict(iterable) -> new dictionary initialized as if via:

    d = ValueSortedDict()
    for k, v in iterable:
        d[k] = v
    
  • ValueSortedDict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example:

    ValueSortedDict(one=1, two=2)
    

An optional key function callable may be specified as the first argument. When so, the callable will be applied to the value of each item pair to determine the comparable for sort order as with Python’s builtin sorted function.

__copy__()

Return shallow copy of the mapping.

__delitem__(key)[source]

del mapping[key]

__init__(*args, **kwargs)[source]

Initialize sorted dict instance.

Optional key-function argument defines a callable that, like the key argument to the built-in sorted function, extracts a comparison key from each dictionary key. If no function is specified, the default compares the dictionary keys directly. The key-function argument must be provided as a positional argument and must come before all other arguments.

Optional iterable argument provides an initial sequence of pairs to initialize the sorted dict. Each pair in the sequence defines the key and corresponding value. If a key is seen more than once, the last value associated with it is stored in the new sorted dict.

Optional mapping argument provides an initial mapping of items to initialize the sorted dict.

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 stored in the sorted dict.

Sorted dict keys must be hashable, per the requirement for Python’s dictionaries. Keys (or the result of the key-function) must also be comparable, per the requirement for sorted lists.

>>> d = {'alpha': 1, 'beta': 2}
>>> SortedDict([('alpha', 1), ('beta', 2)]) == d
True
>>> SortedDict({'alpha': 1, 'beta': 2}) == d
True
>>> SortedDict(alpha=1, beta=2) == d
True
__reduce__()[source]

Support for pickle.

The tricks played with caching references in SortedDict.__init__() confuse pickle so customize the reducer.

__repr__()[source]

Return string representation of sorted dict.

sd.__repr__() <==> repr(sd)

Returns

string representation

__setitem__(key, value)[source]

mapping[key] = value

copy()[source]

Return shallow copy of the mapping.