Nearest Dictionary Recipe

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

A dict using nearest-key lookup.

A SortedDict subclass that uses nearest-key lookup instead of exact-key lookup. Optionally, you can specify a rounding mode to return the nearest key less than or equal to or greater than or equal to the provided key.

When using NearestDict.NEAREST the keys must support subtraction to allow finding the nearest key (by find the key with the smallest difference to the given one).

Additional methods:

Example usage:

>>> d = NearestDict({1.0: 'foo'})
>>> d[1.0]
'foo'
>>> d[0.0]
'foo'
>>> d[2.0]
'foo'
__getitem__(request)[source]

Return item corresponding to nearest_key().

Parameters

request – nearest-key lookup value

Returns

item corresponding to key nearest request

Raises

KeyError – if no appropriate item can be found

>>> d = NearestDict({1.0: 'foo'})
>>> d[0.0]
'foo'
>>> d[2.0]
'foo'
>>> d = NearestDict({1.0: 'foo'}, rounding=NearestDict.NEAREST_NEXT)
>>> d[0.0]
'foo'
>>> d[2.0]
Traceback (most recent call last):
  ...
KeyError: 'No key above 2.0 found'
__init__(*args, **kwargs)[source]

Initialize a NearestDict instance.

Optional rounding argument dictates how NearestDict.nearest_key() rounds. It must be one of NearestDict.NEAREST_NEXT, NearestDict.NEAREST, or NearestDict.NEAREST_PREV. (Default: NearestDict.NEAREST)

Params rounding

how to round on nearest-key lookup (optional)

Params args

positional arguments for SortedDict.

Params kwargs

keyword arguments for SortedDict.

nearest_key(request)[source]

Return nearest-key to request, respecting self.rounding.

>>> d = NearestDict({1.0: 'foo'})
>>> d.nearest_key(0.0)
1.0
>>> d.nearest_key(2.0)
1.0
>>> d = NearestDict({1.0: 'foo'}, rounding=NearestDict.NEAREST_PREV)
>>> d.nearest_key(0.0)
Traceback (most recent call last):
  ...
KeyError: 'No key below 0.0 found'
>>> d.nearest_key(2.0)
1.0
Parameters

request – nearest-key lookup value

Returns

key nearest to request, respecting rounding

Raises

KeyError – if no appropriate key can be found