libutilitaspy.data_structures.maps

Provides utilities for functions, dictionaries, and associative tables.

libutilitaspy.data_structures.maps.dictunion(dict1, dict2)[source]

Returns a dictionary containing all key, value pairs of the given dictionaries.

Parameters:
  • dict1 (dict) – Some dictionary
  • dict2 (dict) – Some dictionary
Returns:

The union of dict1 and dict2

Return type:

dict

class libutilitaspy.data_structures.maps.Map(m, imp=None)[source]

Map objects generalize functions, dictionaries and associative tables. A map object behaves as both.

Map objects can be built from either:

  • a Mapping object, or
  • a Callable object

For example:

m1 = Map({1: 'a', 2: 'b', 3: 'a'})
m2 = Map(lambda x: 'a' if x in (1,3) else 'b')

It can be accessed with both dictionary and function call notation, e.g.:

y1 = m1[3]
y2 = m1(3)

Maps are mutable, even if defined by a function, e.g.:

m1[2] = 'c'
m2[2] = 'd'    # even though m2 was defined with a function rather than a dictionary.

If built from a Mapping object, the underlying Map implementation can be either:

If built from a Callable object, the underlying Map implementation can be either:

  • a function (default), or
  • a memoized function

For example:

m1_1 = Map({1: 'a', 2: 'b', 3: 'a'}, 'dict')   
m1_2 = Map({1: 'a', 2: 'b', 3: 'a'}, 'trie')
m2_1 = Map(lambda x: 'a' if x in (1,3) else 'b', 'func')   
m2_2 = Map(lambda x: 'a' if x in (1,3) else 'b', 'mem')

Many combinations are possible. For example, you can create a map with a dictionary representation from a trie.

Note

A trie representation is useful when the mapping keys are sequences of hashable objects.

A memoized function representation is useful for callables which are pure functions (always return the same output on the same input), are called frequently and perform a significant amount of computation. The trade-off is that memory is used to cache previously computed results.

Parameters:
  • m (Mapping or Callable) – the mapping or callable object to make into a map.
  • imp (str: for Mapping objects it can be ‘dict’ (default) or ‘trie’; for Callable objects it can be ‘func’ (default) or ‘mem’.) – The underlying implementation used
get_preimage(value)[source]
Returns:the pre-image of value, this is, the set of keys or indices or source values of the map, whose image is value.
Return type:set
Note :This method is available if the underlying implementation is a dictionary, a trie or a memoized function, but it is not available if it is a (non-memoized) function.
reflexive_closure()[source]

Returns the reflexive closure of the map, i.e. the map extended with the identity map.

Previous topic

libutilitaspy.data_structures.partitions

Next topic

libutilitaspy.data_structures.graphs

This Page