Adding doctests. Also added a logging filter.
[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, Tuple
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     """
15     Initialize a dict value (if it doesn't exist) or increments it (using the
16     inc_function, which is customizable) if it already does exist.  Returns
17     True if the key already existed or False otherwise.
18
19     >>> d = {}
20     >>> init_or_inc(d, "test")
21     False
22     >>> init_or_inc(d, "test")
23     True
24     >>> init_or_inc(d, 'ing')
25     False
26     >>> d
27     {'test': 2, 'ing': 1}
28
29     """
30     if key in d.keys():
31         d[key] = inc_function(d[key])
32         return True
33     d[key] = init_value
34     return False
35
36
37 def shard(d: Dict[Any, Any], size: int) -> Iterator[Dict[Any, Any]]:
38     """
39     Shards a dict into N subdicts which, together, contain all keys/values
40     from the original unsharded dict.
41     """
42     items = d.items()
43     for x in range(0, len(d), size):
44         yield {key: value for (key, value) in islice(items, x, x + size)}
45
46
47 def coalesce_by_creating_list(key, v1, v2):
48     from list_utils import flatten
49     return flatten([v1, v2])
50
51
52 def coalesce_by_creating_set(key, v1, v2):
53     return set(coalesce_by_creating_list(key, v1, v2))
54
55
56 def raise_on_duplicated_keys(key, v1, v2):
57     raise Exception(f'Key {key} is duplicated in more than one input dict.')
58
59
60 def coalesce(
61         inputs: Iterator[Dict[Any, Any]],
62         *,
63         aggregation_function: Callable[[Any, Any], Any] = coalesce_by_creating_list
64 ) -> Dict[Any, Any]:
65     """Merge N dicts into one dict containing the union of all keys/values in
66     the input dicts.  When keys collide, apply the aggregation_function which,
67     by default, creates a list of values.  See also coalesce_by_creating_set or
68     provide a user defined aggregation_function.
69
70     >>> a = {'a': 1, 'b': 2}
71     >>> b = {'b': 1, 'c': 2, 'd': 3}
72     >>> c = {'c': 1, 'd': 2}
73     >>> coalesce([a, b, c])
74     {'a': 1, 'b': [1, 2], 'c': [1, 2], 'd': [2, 3]}
75
76     """
77     out: Dict[Any, Any] = {}
78     for d in inputs:
79         for key in d:
80             if key in out:
81                 value = aggregation_function(key, d[key], out[key])
82             else:
83                 value = d[key]
84             out[key] = value
85     return out
86
87
88 def item_with_max_value(d: Dict[Any, Any]) -> Tuple[Any, Any]:
89     """Returns the key and value with the max value in a dict.
90
91     >>> d = {'a': 1, 'b': 2, 'c': 3}
92     >>> item_with_max_value(d)
93     ('c', 3)
94     >>> item_with_max_value({})
95     Traceback (most recent call last):
96     ...
97     ValueError: max() arg is an empty sequence
98
99     """
100     return max(d.items(), key=lambda _: _[1])
101
102
103 def item_with_min_value(d: Dict[Any, Any]) -> Tuple[Any, Any]:
104     """Returns the key and value with the min value in a dict.
105
106     >>> d = {'a': 1, 'b': 2, 'c': 3}
107     >>> item_with_min_value(d)
108     ('a', 1)
109
110     """
111     return min(d.items(), key=lambda _: _[1])
112
113
114 def key_with_max_value(d: Dict[Any, Any]) -> Any:
115     """Returns the key with the max value in the dict.
116
117     >>> d = {'a': 1, 'b': 2, 'c': 3}
118     >>> key_with_max_value(d)
119     'c'
120
121     """
122     return item_with_max_value(d)[0]
123
124
125 def key_with_min_value(d: Dict[Any, Any]) -> Any:
126     """Returns the key with the min value in the dict.
127
128     >>> d = {'a': 1, 'b': 2, 'c': 3}
129     >>> key_with_min_value(d)
130     'a'
131
132     """
133     return item_with_min_value(d)[0]
134
135
136 def max_value(d: Dict[Any, Any]) -> Any:
137     """Returns the maximum value in the dict.
138
139     >>> d = {'a': 1, 'b': 2, 'c': 3}
140     >>> max_value(d)
141     3
142
143     """
144     return item_with_max_value(d)[1]
145
146
147 def min_value(d: Dict[Any, Any]) -> Any:
148     """Returns the minimum value in the dict.
149
150     >>> d = {'a': 1, 'b': 2, 'c': 3}
151     >>> min_value(d)
152     1
153
154     """
155     return item_with_min_value(d)[1]
156
157
158 def max_key(d: Dict[Any, Any]) -> Any:
159     """Returns the maximum key in dict (ignoring values totally)
160
161     >>> d = {'a': 3, 'b': 2, 'c': 1}
162     >>> max_key(d)
163     'c'
164
165     """
166     return max(d.keys())
167
168
169 def min_key(d: Dict[Any, Any]) -> Any:
170     """Returns the minimum key in dict (ignoring values totally)
171
172     >>> d = {'a': 3, 'b': 2, 'c': 1}
173     >>> min_key(d)
174     'a'
175
176     """
177     return min(d.keys())
178
179
180 if __name__ == '__main__':
181     import doctest
182     doctest.testmod()