larvaworld.lib.util.dictsNlists
Classes and methods for managing nested dictionaries and lists
Classes
Dictionary subclass with attribute-style access. |
|
Bidirectional dictionary with inverse mapping. |
|
Enhanced list with utility properties and methods. |
|
Agent sequence list with mass attribute setting. |
Functions
|
Load dictionary from pickle or JSON file. |
|
Save dictionary to pickle or JSON file. |
|
Filter column names to those that exist in DataFrame. |
|
Filter column names to those that don't exist in DataFrame. |
|
Check if all columns exist in DataFrame. |
|
Flatten a list of lists into a single list. |
|
Check if two lists contain the same elements (order-independent). |
|
Remove duplicates from list while preserving order. |
|
Convert 2D numpy array to list of tuples. |
Module Contents
- class larvaworld.lib.util.dictsNlists.AttrDict(*args: Any, **kwargs: Any)
Bases:
dictDictionary subclass with attribute-style access.
Allows dictionary entries to be accessed using dot notation (as attributes) in addition to standard bracket notation. Automatically converts nested dictionaries to AttrDict instances.
- Example:
>>> d = AttrDict({'a': 1, 'b': {'c': 2}}) >>> d.a 1 >>> d.b.c 2 >>> d['b']['c'] 2
- autonest(d: dict) dict
- classmethod from_nested_dicts(data: Any) Any
Construct nested NestDicts from nested dictionaries.
- update_existingdict(dic: dict) None
- update_existingdict_by_suffix(dic: dict) None
- save(file: str) None
- print(flat: bool = False) None
- larvaworld.lib.util.dictsNlists.load_dict(file: str) AttrDict
Load dictionary from pickle or JSON file.
Attempts to load from pickle first, falls back to JSON if that fails, returns empty AttrDict if both fail.
- Args:
file: Path to file containing pickled or JSON dictionary
- Returns:
Loaded dictionary as AttrDict, or empty AttrDict on failure
- Example:
>>> d = load_dict('config.pkl') >>> d = load_dict('config.json')
- larvaworld.lib.util.dictsNlists.save_dict(d: dict, file: str) None
Save dictionary to pickle or JSON file.
Attempts to save as pickle first, falls back to JSON if that fails.
- Args:
d: Dictionary to save file: Path to output file
- Example:
>>> save_dict({'a': 1, 'b': 2}, 'config.pkl') >>> save_dict({'a': 1, 'b': 2}, 'config.json')
- class larvaworld.lib.util.dictsNlists.bidict(*args: Any, **kwargs: Any)
Bases:
dictBidirectional dictionary with inverse mapping.
Maintains both forward (key→value) and inverse (value→keys) mappings. The inverse attribute maps each value to a list of keys that map to it.
- Attributes:
inverse: Dictionary mapping values to lists of keys
- Example:
>>> bd = bidict({'a': 1, 'b': 2, 'c': 1}) >>> bd.inverse {1: ['a', 'c'], 2: ['b']} >>> bd['a'] 1
- inverse
- class larvaworld.lib.util.dictsNlists.SuperList
Bases:
listEnhanced list with utility properties and methods.
Extends built-in list with convenient properties for sorting, flattening, deduplication, grouping, and DataFrame column operations.
- Properties:
N: Length of list sorted: Sorted copy of list flatten: Recursively flattened list unique: List with duplicates removed (preserves order) in_pairs: List grouped into pairs
- Example:
>>> sl = SuperList([3, 1, 2, 1]) >>> sl.unique [3, 1, 2] >>> sl.sorted [1, 1, 2, 3] >>> SuperList([[1, 2], [3, 4]]).flatten [1, 2, 3, 4]
- property N: int
- exist_in(df) bool
- class larvaworld.lib.util.dictsNlists.ItemList(objs=(), cls=None, *args: Any, **kwargs: Any)
Bases:
agentpy.sequences.AgentSequence,listAgent sequence list with mass attribute setting.
Combines agentpy.AgentSequence with list functionality, allowing batch attribute operations on agent collections.
- Example:
>>> items = ItemList([agent1, agent2, agent3]) >>> items.speed = 5.0 # Sets speed=5.0 on all agents
- larvaworld.lib.util.dictsNlists.existing_cols(cols: list[str], df: pandas.DataFrame | list[str]) list[str]
Filter column names to those that exist in DataFrame.
- Args:
cols: List of column names to check df: DataFrame or list of column names
- Returns:
List of columns from cols that exist in df
- Example:
>>> existing_cols(['a', 'b', 'c'], df) ['a', 'c'] # if only 'a' and 'c' exist in df
- larvaworld.lib.util.dictsNlists.nonexisting_cols(cols: list[str], df: pandas.DataFrame | list[str]) list[str]
Filter column names to those that don’t exist in DataFrame.
- Args:
cols: List of column names to check df: DataFrame or list of column names
- Returns:
List of columns from cols that don’t exist in df
- Example:
>>> nonexisting_cols(['a', 'b', 'c'], df) ['b'] # if only 'b' doesn't exist in df
- larvaworld.lib.util.dictsNlists.cols_exist(cols: list[str], df: pandas.DataFrame | list[str]) bool
Check if all columns exist in DataFrame.
- Args:
cols: List of column names to check df: DataFrame or list of column names
- Returns:
True if all columns in cols exist in df
- Example:
>>> cols_exist(['a', 'b'], df) True # if both 'a' and 'b' exist
- larvaworld.lib.util.dictsNlists.flatten_list(l: list[list[Any]]) list[Any]
Flatten a list of lists into a single list.
- Args:
l: List of lists to flatten
- Returns:
Flattened list containing all items from sublists
- Example:
>>> flatten_list([[1, 2], [3, 4], [5]]) [1, 2, 3, 4, 5]
- larvaworld.lib.util.dictsNlists.checkEqual(l1: list[Any], l2: list[Any]) bool
Check if two lists contain the same elements (order-independent).
- Args:
l1: First list l2: Second list
- Returns:
True if both lists contain exactly the same elements
- Example:
>>> checkEqual([1, 2, 3], [3, 2, 1]) True >>> checkEqual([1, 2], [1, 2, 3]) False
- larvaworld.lib.util.dictsNlists.unique_list(l: list[Any]) SuperList
Remove duplicates from list while preserving order.
- Args:
l: List to deduplicate
- Returns:
SuperList with duplicates removed, first occurrence preserved
- Example:
>>> unique_list([1, 2, 1, 3, 2]) [1, 2, 3]
- larvaworld.lib.util.dictsNlists.np2Dtotuples(a: Any) list[tuple[Any, Any]]
Convert 2D numpy array to list of tuples.
- Args:
a: 2D numpy array with shape (N, 2) or list of tuples
- Returns:
List of (x, y) tuples
- Example:
>>> arr = np.array([[1, 2], [3, 4]]) >>> np2Dtotuples(arr) [(1, 2), (3, 4)]