X-Git-Url: https://wannabe.guru.org/gitweb/?a=blobdiff_plain;f=src%2Fpyutils%2Fdict_utils.py;h=8e6d6cb9b3c357398104a6b48af61064d4f77217;hb=HEAD;hp=a675213a60ab7597b1bfb69a3d77c0c2a652b3f0;hpb=91532da029f97392d23a69e35b55bdff6b7ac4e5;p=pyutils.git diff --git a/src/pyutils/dict_utils.py b/src/pyutils/dict_utils.py index a675213..8e6d6cb 100644 --- a/src/pyutils/dict_utils.py +++ b/src/pyutils/dict_utils.py @@ -21,14 +21,17 @@ def init_or_inc( init_value: Any = 1, inc_function: Callable[..., Any] = lambda x: x + 1, ) -> bool: - """ - Initialize a dict value (if it doesn't exist) or increments it (using the + """Initialize a dict value (if it doesn't exist) or increments it (using the inc_function, which is customizable) if it already does exist. + See also :py:class:`defaultdict` + (https://docs.python.org/3/library/collections.html#collections.defaultdict) + for a more pythonic alternative. + Args: d: the dict to increment or initialize a value in key: the key to increment or initialize - init_value: default initial value + init_value: default initial value (see also :meth:`dict.setdefault`) inc_function: Callable use to increment a value Returns: @@ -46,6 +49,7 @@ def init_or_inc( False >>> d {'test': 2, 'ing': 1} + """ if key in d.keys(): d[key] = inc_function(d[key]) @@ -333,13 +337,16 @@ def parallel_lists_to_dict(keys: List[Hashable], values: List[Any]) -> AnyDict: Returns: A dict composed of zipping the keys list and values list together. + Raises: + ValueError: if keys and values lists not the same length. + >>> k = ['name', 'phone', 'address', 'zip'] >>> v = ['scott', '555-1212', '123 main st.', '12345'] >>> parallel_lists_to_dict(k, v) {'name': 'scott', 'phone': '555-1212', 'address': '123 main st.', 'zip': '12345'} """ if len(keys) != len(values): - raise Exception("Parallel keys and values lists must have the same length") + raise ValueError("Parallel keys and values lists must have the same length") return dict(zip(keys, values))