[docs]defflatten_dict(dictionary:DictStrAny,seperator:str)->list[str]:"""Flatten a nested dictionary. Args: dictionary (DictStrAny): The dictionary to flatten. seperator (str): The seperator to use between keys. Returns: List[str]: A list of flattened keys. Examples: >>> d = {'a': {'b': {'c': 10}}} >>> flatten_dict(d, '.') ['a.b.c'] """flattened=[]forkey,valueindictionary.items():ifisinstance(value,dict):flattened.extend([f"{key}{seperator}{subkey}"forsubkeyinflatten_dict(value,seperator)])else:flattened.append(key)returnflattened
[docs]defget_dict_nested(# type: ignoredictionary:DictStrAny,keys:list[str],allow_missing:bool=False)->Any:"""Get a value from a nested dictionary. Args: 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: list[str]: The value from the dictionary. 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']) """forkeyinkeys:ifkeynotindictionary:ifallow_missing:returnNoneraiseValueError(f"Key {key} not in dictionary! Current keys: "f"{dictionary.keys()}")dictionary=dictionary[key]returndictionary
[docs]defset_dict_nested(# type: ignoredictionary:DictStrAny,keys:list[str],value:Any)->None:"""Set a value in a nested dictionary. Args: 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. Examples: >>> d = {} >>> set_dict_nested(d, ['a', 'b', 'c'], 10) >>> d {'a': {'b': {'c': 10}}} """forkeyinkeys[:-1]:dictionary=dictionary.setdefault(key,{})dictionary[keys[-1]]=value