diff options
| author | Scott Gasch <[email protected]> | 2021-03-24 18:08:54 -0700 |
|---|---|---|
| committer | Scott Gasch <[email protected]> | 2021-03-24 18:08:54 -0700 |
| commit | 497fb9e21f45ec08e1486abaee6dfa7b20b8a691 (patch) | |
| tree | 47aa97a0fca36c4e7025cee5ad4e9ec6db49b881 /dict_utils.py | |
Initial revision
Diffstat (limited to 'dict_utils.py')
| -rw-r--r-- | dict_utils.py | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/dict_utils.py b/dict_utils.py new file mode 100644 index 0000000..29a5cd0 --- /dev/null +++ b/dict_utils.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 + +from itertools import islice +from typing import Any, Callable, Dict, Iterator + + +def init_or_inc( + d: Dict[Any, Any], + key: Any, + *, + init_value: Any = 1, + inc_function: Callable[..., Any] = lambda x: x + 1 +) -> bool: + if key in d.keys(): + d[key] = inc_function(d[key]) + return True + d[key] = init_value + return False + + +def shard(d: Dict[Any, Any], size: int) -> Iterator[Dict[Any, Any]]: + items = d.items() + for x in range(0, len(d), size): + yield {key: value for (key, value) in islice(items, x, x + size)} + + +def item_with_max_value(d: Dict[Any, Any]) -> Any: + return max(d.items(), key=lambda _: _[1]) + + +def item_with_min_value(d: Dict[Any, Any]) -> Any: + return min(d.items(), key=lambda _: _[1]) + + +def key_with_max_value(d: Dict[Any, Any]) -> Any: + return item_with_max_value(d)[0] + + +def key_with_min_value(d: Dict[Any, Any]) -> Any: + return item_with_min_value(d)[0] + + +def max_value(d: Dict[Any, Any]) -> Any: + return item_with_max_value(d)[1] + + +def min_value(d: Dict[Any, Any]) -> Any: + return item_with_min_value(d)[1] + + +def max_key(d: Dict[Any, Any]) -> Any: + return max(d.keys()) + + +def min_key(d: Dict[Any, Any]) -> Any: + return min(d.keys()) + + +def merge(a: Dict[Any, Any], b: Dict[Any, Any], path=None) -> Dict[Any, Any]: + if path is None: + path = [] + for key in b: + if key in a: + if isinstance(a[key], dict) and isinstance(b[key], dict): + merge(a[key], b[key], path + [str(key)]) + elif a[key] == b[key]: + pass + else: + raise Exception("Conflict at %s" % ".".join(path + [str(key)])) + else: + a[key] = b[key] + return a |
