3 """Helper functions for dealing with dictionaries."""
5 from itertools import islice
6 from typing import Any, Callable, Dict, Iterator, List, Tuple
14 inc_function: Callable[..., Any] = lambda x: x + 1,
17 Initialize a dict value (if it doesn't exist) or increments it (using the
18 inc_function, which is customizable) if it already does exist. Returns
19 True if the key already existed or False otherwise.
22 >>> init_or_inc(d, "test")
24 >>> init_or_inc(d, "test")
26 >>> init_or_inc(d, 'ing')
33 d[key] = inc_function(d[key])
39 def shard(d: Dict[Any, Any], size: int) -> Iterator[Dict[Any, Any]]:
41 Shards a dict into N subdicts which, together, contain all keys/values
42 from the original unsharded dict.
46 for x in range(0, len(d), size):
47 yield dict(islice(items, x, x + size))
50 def coalesce_by_creating_list(_, new_value, old_value):
51 from list_utils import flatten
53 return flatten([new_value, old_value])
56 def coalesce_by_creating_set(key, new_value, old_value):
57 return set(coalesce_by_creating_list(key, new_value, old_value))
60 def coalesce_last_write_wins(_, new_value, discarded_old_value):
64 def coalesce_first_write_wins(_, discarded_new_value, old_value):
68 def raise_on_duplicated_keys(key, new_value, old_value):
69 raise Exception(f'Key {key} is duplicated in more than one input dict.')
73 inputs: Iterator[Dict[Any, Any]],
75 aggregation_function: Callable[[Any, Any, Any], Any] = coalesce_by_creating_list,
77 """Merge N dicts into one dict containing the union of all keys /
78 values in the input dicts. When keys collide, apply the
79 aggregation_function which, by default, creates a list of values.
80 See also several other alternative functions for coalescing values
81 (coalesce_by_creating_set, coalesce_first_write_wins,
82 coalesce_last_write_wins, raise_on_duplicated_keys) or provide a
83 custom helper function.
85 >>> a = {'a': 1, 'b': 2}
86 >>> b = {'b': 1, 'c': 2, 'd': 3}
87 >>> c = {'c': 1, 'd': 2}
88 >>> coalesce([a, b, c])
89 {'a': 1, 'b': [1, 2], 'c': [1, 2], 'd': [2, 3]}
91 >>> coalesce([a, b, c], aggregation_function=coalesce_last_write_wins)
92 {'a': 1, 'b': 1, 'c': 1, 'd': 2}
94 >>> coalesce([a, b, c], aggregation_function=raise_on_duplicated_keys)
95 Traceback (most recent call last):
97 Exception: Key b is duplicated in more than one input dict.
100 out: Dict[Any, Any] = {}
104 value = aggregation_function(key, d[key], out[key])
111 def item_with_max_value(d: Dict[Any, Any]) -> Tuple[Any, Any]:
112 """Returns the key and value with the max value in a dict.
114 >>> d = {'a': 1, 'b': 2, 'c': 3}
115 >>> item_with_max_value(d)
117 >>> item_with_max_value({})
118 Traceback (most recent call last):
120 ValueError: max() arg is an empty sequence
123 return max(d.items(), key=lambda _: _[1])
126 def item_with_min_value(d: Dict[Any, Any]) -> Tuple[Any, Any]:
127 """Returns the key and value with the min value in a dict.
129 >>> d = {'a': 1, 'b': 2, 'c': 3}
130 >>> item_with_min_value(d)
134 return min(d.items(), key=lambda _: _[1])
137 def key_with_max_value(d: Dict[Any, Any]) -> Any:
138 """Returns the key with the max value in the dict.
140 >>> d = {'a': 1, 'b': 2, 'c': 3}
141 >>> key_with_max_value(d)
145 return item_with_max_value(d)[0]
148 def key_with_min_value(d: Dict[Any, Any]) -> Any:
149 """Returns the key with the min value in the dict.
151 >>> d = {'a': 1, 'b': 2, 'c': 3}
152 >>> key_with_min_value(d)
156 return item_with_min_value(d)[0]
159 def max_value(d: Dict[Any, Any]) -> Any:
160 """Returns the maximum value in the dict.
162 >>> d = {'a': 1, 'b': 2, 'c': 3}
167 return item_with_max_value(d)[1]
170 def min_value(d: Dict[Any, Any]) -> Any:
171 """Returns the minimum value in the dict.
173 >>> d = {'a': 1, 'b': 2, 'c': 3}
178 return item_with_min_value(d)[1]
181 def max_key(d: Dict[Any, Any]) -> Any:
182 """Returns the maximum key in dict (ignoring values totally)
184 >>> d = {'a': 3, 'b': 2, 'c': 1}
192 def min_key(d: Dict[Any, Any]) -> Any:
193 """Returns the minimum key in dict (ignoring values totally)
195 >>> d = {'a': 3, 'b': 2, 'c': 1}
203 def parallel_lists_to_dict(keys: List[Any], values: List[Any]) -> Dict[Any, Any]:
204 """Given two parallel lists (keys and values), create and return
207 >>> k = ['name', 'phone', 'address', 'zip']
208 >>> v = ['scott', '555-1212', '123 main st.', '12345']
209 >>> parallel_lists_to_dict(k, v)
210 {'name': 'scott', 'phone': '555-1212', 'address': '123 main st.', 'zip': '12345'}
213 if len(keys) != len(values):
214 raise Exception("Parallel keys and values lists must have the same length")
215 return dict(zip(keys, values))
218 def dict_to_key_value_lists(d: Dict[Any, Any]) -> Tuple[List[Any], List[Any]]:
220 >>> d = {'name': 'scott', 'phone': '555-1212', 'address': '123 main st.', 'zip': '12345'}
221 >>> (k, v) = dict_to_key_value_lists(d)
223 ['name', 'phone', 'address', 'zip']
225 ['scott', '555-1212', '123 main st.', '12345']
228 r: Tuple[List[Any], List[Any]] = ([], [])
229 for (k, v) in d.items():
235 if __name__ == '__main__':