3 from itertools import islice
4 from typing import Any, Callable, Dict, Iterator, List, Tuple
12 inc_function: Callable[..., Any] = lambda x: x + 1
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.
20 >>> init_or_inc(d, "test")
22 >>> init_or_inc(d, "test")
24 >>> init_or_inc(d, 'ing')
31 d[key] = inc_function(d[key])
37 def shard(d: Dict[Any, Any], size: int) -> Iterator[Dict[Any, Any]]:
39 Shards a dict into N subdicts which, together, contain all keys/values
40 from the original unsharded dict.
43 for x in range(0, len(d), size):
44 yield {key: value for (key, value) in islice(items, x, x + size)}
47 def coalesce_by_creating_list(key, new_value, old_value):
48 from list_utils import flatten
49 return flatten([new_value, old_value])
52 def coalesce_by_creating_set(key, new_value, old_value):
53 return set(coalesce_by_creating_list(key, new_value, old_value))
56 def coalesce_last_write_wins(key, new_value, old_value):
60 def coalesce_first_write_wins(key, new_value, old_value):
64 def raise_on_duplicated_keys(key, new_value, old_value):
65 raise Exception(f'Key {key} is duplicated in more than one input dict.')
69 inputs: Iterator[Dict[Any, Any]],
71 aggregation_function: Callable[[Any, Any], Any] = coalesce_by_creating_list
73 """Merge N dicts into one dict containing the union of all keys /
74 values in the input dicts. When keys collide, apply the
75 aggregation_function which, by default, creates a list of values.
76 See also several other alternative functions for coalescing values
77 (coalesce_by_creating_set, coalesce_first_write_wins,
78 coalesce_last_write_wins, raise_on_duplicated_keys) or provide a
79 custom helper function.
81 >>> a = {'a': 1, 'b': 2}
82 >>> b = {'b': 1, 'c': 2, 'd': 3}
83 >>> c = {'c': 1, 'd': 2}
84 >>> coalesce([a, b, c])
85 {'a': 1, 'b': [1, 2], 'c': [1, 2], 'd': [2, 3]}
87 >>> coalesce([a, b, c], aggregation_function=coalesce_last_write_wins)
88 {'a': 1, 'b': 1, 'c': 1, 'd': 2}
90 >>> coalesce([a, b, c], aggregation_function=raise_on_duplicated_keys)
91 Traceback (most recent call last):
93 Exception: Key b is duplicated in more than one input dict.
96 out: Dict[Any, Any] = {}
100 value = aggregation_function(key, d[key], out[key])
107 def item_with_max_value(d: Dict[Any, Any]) -> Tuple[Any, Any]:
108 """Returns the key and value with the max value in a dict.
110 >>> d = {'a': 1, 'b': 2, 'c': 3}
111 >>> item_with_max_value(d)
113 >>> item_with_max_value({})
114 Traceback (most recent call last):
116 ValueError: max() arg is an empty sequence
119 return max(d.items(), key=lambda _: _[1])
122 def item_with_min_value(d: Dict[Any, Any]) -> Tuple[Any, Any]:
123 """Returns the key and value with the min value in a dict.
125 >>> d = {'a': 1, 'b': 2, 'c': 3}
126 >>> item_with_min_value(d)
130 return min(d.items(), key=lambda _: _[1])
133 def key_with_max_value(d: Dict[Any, Any]) -> Any:
134 """Returns the key with the max value in the dict.
136 >>> d = {'a': 1, 'b': 2, 'c': 3}
137 >>> key_with_max_value(d)
141 return item_with_max_value(d)[0]
144 def key_with_min_value(d: Dict[Any, Any]) -> Any:
145 """Returns the key with the min value in the dict.
147 >>> d = {'a': 1, 'b': 2, 'c': 3}
148 >>> key_with_min_value(d)
152 return item_with_min_value(d)[0]
155 def max_value(d: Dict[Any, Any]) -> Any:
156 """Returns the maximum value in the dict.
158 >>> d = {'a': 1, 'b': 2, 'c': 3}
163 return item_with_max_value(d)[1]
166 def min_value(d: Dict[Any, Any]) -> Any:
167 """Returns the minimum value in the dict.
169 >>> d = {'a': 1, 'b': 2, 'c': 3}
174 return item_with_min_value(d)[1]
177 def max_key(d: Dict[Any, Any]) -> Any:
178 """Returns the maximum key in dict (ignoring values totally)
180 >>> d = {'a': 3, 'b': 2, 'c': 1}
188 def min_key(d: Dict[Any, Any]) -> Any:
189 """Returns the minimum key in dict (ignoring values totally)
191 >>> d = {'a': 3, 'b': 2, 'c': 1}
199 def parallel_lists_to_dict(keys: List[Any], values: List[Any]) -> Dict[Any, Any]:
200 """Given two parallel lists (keys and values), create and return
203 >>> k = ['name', 'phone', 'address', 'zip']
204 >>> v = ['scott', '555-1212', '123 main st.', '12345']
205 >>> parallel_lists_to_dict(k, v)
206 {'name': 'scott', 'phone': '555-1212', 'address': '123 main st.', 'zip': '12345'}
209 if len(keys) != len(values):
210 raise Exception("Parallel keys and values lists must have the same length")
211 return dict(zip(keys, values))
214 def dict_to_key_value_lists(d: Dict[Any, Any]) -> Tuple[List[Any], List[Any]]:
216 >>> d = {'name': 'scott', 'phone': '555-1212', 'address': '123 main st.', 'zip': '12345'}
217 >>> (k, v) = dict_to_key_value_lists(d)
219 ['name', 'phone', 'address', 'zip']
221 ['scott', '555-1212', '123 main st.', '12345']
225 for (k, v) in d.items():
231 if __name__ == '__main__':