Columnify text.
[python_utils.git] / dict_utils.py
1 #!/usr/bin/env python3
2
3 from itertools import islice
4 from typing import Any, Callable, Dict, Iterator
5
6
7 def init_or_inc(
8     d: Dict[Any, Any],
9     key: Any,
10     *,
11     init_value: Any = 1,
12     inc_function: Callable[..., Any] = lambda x: x + 1
13 ) -> bool:
14     if key in d.keys():
15         d[key] = inc_function(d[key])
16         return True
17     d[key] = init_value
18     return False
19
20
21 def shard(d: Dict[Any, Any], size: int) -> Iterator[Dict[Any, Any]]:
22     items = d.items()
23     for x in range(0, len(d), size):
24         yield {key: value for (key, value) in islice(items, x, x + size)}
25
26
27 def item_with_max_value(d: Dict[Any, Any]) -> Any:
28     return max(d.items(), key=lambda _: _[1])
29
30
31 def item_with_min_value(d: Dict[Any, Any]) -> Any:
32     return min(d.items(), key=lambda _: _[1])
33
34
35 def key_with_max_value(d: Dict[Any, Any]) -> Any:
36     return item_with_max_value(d)[0]
37
38
39 def key_with_min_value(d: Dict[Any, Any]) -> Any:
40     return item_with_min_value(d)[0]
41
42
43 def max_value(d: Dict[Any, Any]) -> Any:
44     return item_with_max_value(d)[1]
45
46
47 def min_value(d: Dict[Any, Any]) -> Any:
48     return item_with_min_value(d)[1]
49
50
51 def max_key(d: Dict[Any, Any]) -> Any:
52     return max(d.keys())
53
54
55 def min_key(d: Dict[Any, Any]) -> Any:
56     return min(d.keys())
57
58
59 def merge(a: Dict[Any, Any], b: Dict[Any, Any], path=None) -> Dict[Any, Any]:
60     if path is None:
61         path = []
62     for key in b:
63         if key in a:
64             if isinstance(a[key], dict) and isinstance(b[key], dict):
65                 merge(a[key], b[key], path + [str(key)])
66             elif a[key] == b[key]:
67                 pass
68             else:
69                 raise Exception("Conflict at %s" % ".".join(path + [str(key)]))
70         else:
71             a[key] = b[key]
72     return a