DictManager#
- class brainstate.util.DictManager(*args, **kwargs)#
Enhanced dictionary for managing collections in BrainState.
DictManager extends the standard Python dict with additional methods for filtering, splitting, and managing collections of objects. It’s registered as a JAX pytree node for compatibility with JAX transformations.
Examples
>>> dm = DictManager({'a': 1, 'b': 2.0, 'c': 'text'}) >>> dm.subset(int) # Get only integer values DictManager({'a': 1}) >>> dm.unique() # Get unique values only DictManager({'a': 1, 'b': 2.0, 'c': 'text'})
- add_unique_key(key, val)[source]#
Add a new element ensuring the key maps to a unique value.
- Parameters:
- Raises:
ValueError – If the key already exists with a different value.
- Return type:
- add_unique_value(key, val)[source]#
Add a new element only if the value is unique across all entries.
- difference_by_values(values, by='id')[source]#
Get items whose values are not in the specified collection.
- Return type:
- filter_by_predicate(predicate)[source]#
Filter items using a predicate function.
- intersection_by_values(values, by='id')[source]#
Get items whose values are in the specified collection.
- Return type:
- map_keys(func)[source]#
Apply a function to all keys.
- Parameters:
func (
Callable[[TypeVar(K)],Any]) – Function to apply to each key.- Returns:
A new DictManager with transformed keys.
- Return type:
- Raises:
ValueError – If the transformation creates duplicate keys.
- map_values(func)[source]#
Apply a function to all values.
- not_subset(sep)[source]#
Get a new DictManager excluding items of specified types.
- split(*types)[source]#
Split the DictManager into multiple based on value types.
- Parameters:
*types (
Type) – Types to use for splitting. Each type gets its own DictManager.- Returns:
A tuple of DictManagers, one for each type plus one for unmatched items.
- Return type:
- subset(sep)[source]#
Get a new DictManager with a subset of items based on value type or predicate.
- Parameters:
sep (
Type|Tuple[Type,...] |Callable[[Any],bool]) – If Type or Tuple of Types: Select values that are instances of these types. If Callable: Select values where sep(value) returns True.- Returns:
A new DictManager containing only matching items.
- Return type:
Examples
>>> dm = DictManager({'a': 1, 'b': 2.0, 'c': 'text'}) >>> dm.subset(int) DictManager({'a': 1}) >>> dm.subset(lambda x: isinstance(x, (int, float))) DictManager({'a': 1, 'b': 2.0})
- unique()[source]#
Get a new DictManager with unique values only.
If multiple keys map to the same value (by identity), only the first key-value pair is retained.
- Returns:
A new DictManager with unique values.
- Return type: