larvaworld.lib.util.dictsNlists

Classes and methods for managing nested dictionaries and lists

Classes

AttrDict

Dictionary subclass with attribute-style access.

bidict

Bidirectional dictionary with inverse mapping.

SuperList

Enhanced list with utility properties and methods.

ItemList

Agent sequence list with mass attribute setting.

Functions

load_dict(→ AttrDict)

Load dictionary from pickle or JSON file.

save_dict(→ None)

Save dictionary to pickle or JSON file.

existing_cols(→ list[str])

Filter column names to those that exist in DataFrame.

nonexisting_cols(→ list[str])

Filter column names to those that don't exist in DataFrame.

cols_exist(→ bool)

Check if all columns exist in DataFrame.

flatten_list(→ list[Any])

Flatten a list of lists into a single list.

checkEqual(→ bool)

Check if two lists contain the same elements (order-independent).

unique_list(→ SuperList)

Remove duplicates from list while preserving order.

np2Dtotuples(→ list[tuple[Any, Any]])

Convert 2D numpy array to list of tuples.

Module Contents

class larvaworld.lib.util.dictsNlists.AttrDict(*args: Any, **kwargs: Any)

Bases: 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
autonest(d: dict) dict
classmethod from_nested_dicts(data: Any) Any

Construct nested NestDicts from nested dictionaries.

replace_keys(pairs: dict = {}) AttrDict
get_copy() AttrDict
flatten(parent_key: str = '', sep: str = '.') AttrDict
unflatten(sep: str = '.') AttrDict
update_existingdict(dic: dict) None
update_existingdict_by_suffix(dic: dict) None
update_nestdict(dic: dict) AttrDict
update_nestdict_copy(dic: dict) AttrDict
new_dict(dic: dict) AttrDict
update_existingnestdict(dic: dict) AttrDict
update_existingnestdict_by_suffix(dic: dict) AttrDict
save(file: str) None
classmethod load(file: str) AttrDict
print(flat: bool = False) None
property keylist: SuperList
classmethod merge_dicts(l: list[dict]) AttrDict
classmethod merge_nestdicts(l: list[dict]) AttrDict
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: 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
inverse
class larvaworld.lib.util.dictsNlists.SuperList

Bases: 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]
property N: int
property sorted: SuperList
property flatten: SuperList
property unique: SuperList
group_by_n(n: int = 2) SuperList
property in_pairs: SuperList
existing(df) SuperList
nonexisting(df) SuperList
exist_in(df) bool
suf(suf: str = '') SuperList
pref(pref: str = '') SuperList
contains(l: str = '') SuperList
class larvaworld.lib.util.dictsNlists.ItemList(objs=(), cls=None, *args: Any, **kwargs: Any)

Bases: agentpy.sequences.AgentSequence, 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
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)]