2019-02-06 21:32:42 -08:00
|
|
|
import itertools as it
|
2018-03-30 18:19:23 -07:00
|
|
|
|
2018-04-06 13:58:59 -07:00
|
|
|
|
2019-02-06 21:32:42 -08:00
|
|
|
def merge_dicts_recursively(*dicts):
|
2018-11-29 17:30:19 -08:00
|
|
|
"""
|
|
|
|
Creates a dict whose keyset is the union of all the
|
|
|
|
input dictionaries. The value for each key is based
|
|
|
|
on the first dict in the list with that key.
|
|
|
|
|
2019-02-06 21:32:42 -08:00
|
|
|
dicts later in the list have higher priority
|
2019-02-06 21:16:26 -08:00
|
|
|
|
2018-11-29 17:30:19 -08:00
|
|
|
When values are dictionaries, it is applied recursively
|
|
|
|
"""
|
2019-02-06 21:32:42 -08:00
|
|
|
result = dict()
|
|
|
|
all_items = it.chain(*[d.items() for d in dicts])
|
|
|
|
for key, value in all_items:
|
|
|
|
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
|
|
|
|
result[key] = merge_dicts_recursively(result[key], value)
|
2018-03-30 18:19:23 -07:00
|
|
|
else:
|
2019-02-06 21:32:42 -08:00
|
|
|
result[key] = value
|
|
|
|
return result
|
2018-03-30 18:19:23 -07:00
|
|
|
|
2018-04-06 13:58:59 -07:00
|
|
|
|
2018-03-30 18:19:23 -07:00
|
|
|
def soft_dict_update(d1, d2):
|
|
|
|
"""
|
|
|
|
Adds key values pairs of d2 to d1 only when d1 doesn't
|
|
|
|
already have that key
|
|
|
|
"""
|
2018-08-09 17:56:05 -07:00
|
|
|
for key, value in list(d2.items()):
|
2018-03-30 18:19:23 -07:00
|
|
|
if key not in d1:
|
|
|
|
d1[key] = value
|