82. odict — Specialized dictionary types.

82.1. Classes defined in module odict

class odict.DDict(default=None, *args, **kargs)[source]

A dict with multiple ways to set the default values.

This is equivalent to the dict class, except that if a key is not found it’s value may be found from calling a function or from looking it up in another dict.

This differs in two ways from the collections.defaultdict class:

  • the default function takes the missing key as a parameter,
  • the value looked up through the default function is not stored in the DDict itself, but will be looked up againe with the default function on each subsequent access of the same key. See EDict for an analog class that stores the looked up values in itself.

Parameters:

  • default: either None, a function. If it is a function, it should take the key as parameter and return the value for that key. It can appropriately be set to the get method of another dict, to have missing keys being looked up in another dict. The default None will cause a KeyError on missing keys.
  • all other parameters are passed to the dict initialisation.

Examples:

>>> d = DDict(lambda x:-x)
>>> print(d)
{}
>>> print(d[1],d[2],d[3])
-1 -2 -3
>>> d[2] = 2
>>> e = DDict(d.get,{1:1})
>>> print(e)
{1: 1}
>>> print(e[1],e[2],e[3])
1 2 None
class odict.EDict(factory=None, *args, **kargs)[source]

An extensible DDict

This class is like DDict, but it installs missing keys in itself, with the value of the first default lookup.

Examples (compare with DDict):

>>> d = EDict(lambda x:-x)
>>> print(d)
{}
>>> print(d[1],d[2],d[3])
-1 -2 -3
>>> d[2] = 2
>>> e = EDict(d.get,{1:1})
>>> print(e)
{1: 1}
>>> print(e[1],e[2],e[3])
1 2 -3