stormvogel.rdict

Functionality for handling nested dictionaries easily.

Functions

rget(→ Any)

Recursively get a dict value.

rset(→ dict)

Recursively set a dict value.

merge_dict(→ dict)

Merge two nested dictionaries recursively.

Module Contents

stormvogel.rdict.rget(d: dict, path: list) Any

Recursively get a dict value.

Parameters:
  • d – The dictionary to query.

  • path – A list of keys forming the path to the desired value.

Returns:

The value at the given path.

Raises:

KeyError – If a key along the path is not present.

Example: rget(d, ['a', 'b', 'c']) is equivalent to d['a']['b']['c'].

stormvogel.rdict.rset(d: dict, path: list[str], value: Any, create_new_keys: bool = False) dict

Recursively set a dict value.

Parameters:
  • d – The dictionary to modify.

  • path – A list of keys that lead to the value to set.

  • value – The target value.

  • create_new_keys – If a key on the path does not exist yet, create it.

Example: rset(d, ['a', 'b', 'c'], 5) is equivalent to d['a']['b']['c'] = 5.

stormvogel.rdict.merge_dict(dict1: dict, dict2: dict) dict

Merge two nested dictionaries recursively.

Note that dict1 is modified by reference and also returned.

Parameters:
  • dict1 – The base dictionary (modified in place).

  • dict2 – The dictionary to merge in. Gets priority in most cases.

In general, dict2 gets priority:

  • If dict2 has a value that dict1 does not have, the value in dict2 is chosen.

  • If both have the same key and both are values, dict2 is chosen.

  • If both have the same key and both are dictionaries, they are merged recursively.

  • If dict1 has a dictionary and dict2 has a value with the same key, dict1 gets priority.

Taken from StackOverflow user Anatoliy R on July 2 2024. https://stackoverflow.com/questions/43797333/how-to-merge-two-nested-dict-in-python