Value Sorted Dictionary Recipe

class sortedcollections.ValueSortedDict(*args, **kwargs)

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)

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.

__reduce__()

helper for pickle

__repr__()

Return repr(self).

__setitem__(key, value)

mapping[key] = value

copy()

Return shallow copy of the mapping.