vis4d.common.dict¶
This module contains dictionary utility functions.
Functions
|
Flatten a nested dictionary. |
|
Get a value from a nested dictionary. |
|
Set a value in a nested dictionary. |
- flatten_dict(dictionary, seperator)[source]¶
Flatten a nested dictionary.
- Parameters:
dictionary (DictStrAny) – The dictionary to flatten.
seperator (str) – The seperator to use between keys.
- Returns:
A list of flattened keys.
- Return type:
List[str]
Examples
>>> d = {'a': {'b': {'c': 10}}} >>> flatten_dict(d, '.') ['a.b.c']
- get_dict_nested(dictionary, keys, allow_missing=False)[source]¶
Get a value from a nested dictionary.
- Parameters:
dictionary (DictStrAny) – The dictionary to get the value from.
keys (list[str]) – A list of keys specifying the location in the nested dictionary where the value is located.
allow_missing (bool, optional) – Whether to allow missing keys. Defaults to False. If False, a ValueError is raised if a key is not present, otherwise None is returned.
- Returns:
The value from the dictionary.
- Return type:
list[str]
- Raises:
ValueError – If the key is not present in the dictionary.
Examples
>>> d = {'a': {'b': {'c': 10}}} >>> get_dict_nested(d, ['a', 'b', 'c']) 10
>>> get_dict_nested(d, ['a', 'b', 'd']) ValueError: Key d not in dictionary! Current keys: dict_keys(['c'])
- set_dict_nested(dictionary, keys, value)[source]¶
Set a value in a nested dictionary.
- Parameters:
dictionary (dict[str, Any]) – The dictionary to set the value in.
keys (list[str]) – A list of keys specifying the location in the nested dictionary where the value should be set.
value (Any) – The value to set in the dictionary.
- Return type:
None
Examples
>>> d = {} >>> set_dict_nested(d, ['a', 'b', 'c'], 10) >>> d {'a': {'b': {'c': 10}}}