larvaworld.lib.util.dictsNlists =============================== .. py:module:: larvaworld.lib.util.dictsNlists .. autoapi-nested-parse:: Classes and methods for managing nested dictionaries and lists Classes ------- .. autoapisummary:: larvaworld.lib.util.dictsNlists.AttrDict larvaworld.lib.util.dictsNlists.bidict larvaworld.lib.util.dictsNlists.SuperList larvaworld.lib.util.dictsNlists.ItemList Functions --------- .. autoapisummary:: larvaworld.lib.util.dictsNlists.load_dict larvaworld.lib.util.dictsNlists.save_dict larvaworld.lib.util.dictsNlists.existing_cols larvaworld.lib.util.dictsNlists.nonexisting_cols larvaworld.lib.util.dictsNlists.cols_exist larvaworld.lib.util.dictsNlists.flatten_list larvaworld.lib.util.dictsNlists.checkEqual larvaworld.lib.util.dictsNlists.unique_list larvaworld.lib.util.dictsNlists.np2Dtotuples Module Contents --------------- .. py:class:: AttrDict(*args: Any, **kwargs: Any) Bases: :py:obj:`dict` Dictionary 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 .. py:method:: autonest(d: dict) -> dict .. py:method:: from_nested_dicts(data: Any) -> Any :classmethod: Construct nested NestDicts from nested dictionaries. .. py:method:: replace_keys(pairs: dict = {}) -> AttrDict .. py:method:: get_copy() -> AttrDict .. py:method:: flatten(parent_key: str = '', sep: str = '.') -> AttrDict .. py:method:: unflatten(sep: str = '.') -> AttrDict .. py:method:: update_existingdict(dic: dict) -> None .. py:method:: update_existingdict_by_suffix(dic: dict) -> None .. py:method:: update_nestdict(dic: dict) -> AttrDict .. py:method:: update_nestdict_copy(dic: dict) -> AttrDict .. py:method:: new_dict(dic: dict) -> AttrDict .. py:method:: update_existingnestdict(dic: dict) -> AttrDict .. py:method:: update_existingnestdict_by_suffix(dic: dict) -> AttrDict .. py:method:: save(file: str) -> None .. py:method:: load(file: str) -> AttrDict :classmethod: .. py:method:: print(flat: bool = False) -> None .. py:property:: keylist :type: SuperList .. py:method:: merge_dicts(l: list[dict]) -> AttrDict :classmethod: .. py:method:: merge_nestdicts(l: list[dict]) -> AttrDict :classmethod: .. py:function:: 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') .. py:function:: 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') .. py:class:: bidict(*args: Any, **kwargs: Any) Bases: :py:obj:`dict` Bidirectional 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 .. py:attribute:: inverse .. py:class:: SuperList Bases: :py:obj:`list` Enhanced 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] .. py:property:: N :type: int .. py:property:: sorted :type: SuperList .. py:property:: flatten :type: SuperList .. py:property:: unique :type: SuperList .. py:method:: group_by_n(n: int = 2) -> SuperList .. py:property:: in_pairs :type: SuperList .. py:method:: existing(df) -> SuperList .. py:method:: nonexisting(df) -> SuperList .. py:method:: exist_in(df) -> bool .. py:method:: suf(suf: str = '') -> SuperList .. py:method:: pref(pref: str = '') -> SuperList .. py:method:: contains(l: str = '') -> SuperList .. py:class:: ItemList(objs=(), cls=None, *args: Any, **kwargs: Any) Bases: :py:obj:`agentpy.sequences.AgentSequence`, :py:obj:`list` Agent 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 .. py:function:: 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 .. py:function:: 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 .. py:function:: 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 .. py:function:: 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] .. py:function:: 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 .. py:function:: 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] .. py:function:: 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)]