caldera.utils.dict_join¶
-
caldera.utils.
dict_join
(a, b, out=None, join_fn=None, default_a=Ellipsis, default_b=Ellipsis, keys=None, mode='union')[source]¶ Join two dictionaries. This function merges two dictionaries is various ways. For example, a dictionary of Dict[str, List] can be merged such that, if the two dictionaries share the same key, the lists are concatenated. The join function can be applied to the union of all keys (default) by (mode=”union”), the intersection of the dictionary (mode=”intersection”), only the keys in the left dictionary (`mode=”left”), or keys only in the right dictionary (mode=”right”).
import operator d1 = {'a': [1,2,3], 'b': [1,2] d2 = {'a': [1,2], 'c': [10,20] d3 = dict_join(d1, d2, join_fn=operator.add) print(d3) # {'a': [1,2,3,1,2], 'b': [1,2], 'c': [10,20]}
This can be done such that the first dictionary is updated instead of returning a new dictionary:
d1 = {'a': [1,2,3], 'b': [1,2] d2 = {'a': [1,2], 'c': [10,20] dict_join(d1, d2, d2, join_fn=lambda a, b: a + b print(d2) # {'a': [1,2,3,1,2], 'b': [1,2], 'c': [10,20]} functools.partial(dict_join, join_fv=operator.add
- Parameters
a (
Dict
[~K, ~T]) – First dictionaryb (
Dict
[~K, ~S]) – Second dictionaryout (
Optional
[Dict
]) – The target dictionary. If None, creates a new dictionary.join_fn (
Optional
[Callable
[[~T, ~S], ~V]]) – Join function when both dictionaries share the same key. If not provided, will use the value provided by the second dictionary.default_a (~T) – Default value to use in the case a key is missing from the first dictionary. If defined as Ellipsis (or …), defaults will be ignored.
default_b (~S) – Default value to use in the case a key is missing from the second dictionary. If defined as Ellipsis (or …), defaults will be ignored.
keys (
Optional
[Iterable
[~K]]) – If provided, explicitly join only on specified keys.mode (
str
) – If keys are None, mode specifies which keys to join. “union” (default), means join takes the union of keys from both dictionaries. “intersection” means take intersection of keys for both dictionaries. “left” means use only keys in the first dictionary. “right” means use only keys from the second dictionary.
- Return type
Dict
[~K,Union
[~T, ~S, ~V]]- Returns