Add dict differ helpers from SO answer

dict_differ
Tyler Goodlet 2022-08-11 16:18:05 -04:00
parent b75683879a
commit 2f6e3ad03f
1 changed files with 27 additions and 0 deletions

View File

@ -101,3 +101,30 @@ def percent_change(
new: float, new: float,
) -> float: ) -> float:
return pnl(init, new) * 100. return pnl(init, new) * 100.
def diff_dict(
d1: dict,
d2: dict,
) -> dict:
d1_keys = set(d1.keys())
d2_keys = set(d2.keys())
shared_keys = d1_keys.intersection(d2_keys)
shared_deltas = {o: (d1[o], d2[o]) for o in shared_keys if d1[o] != d2[o]}
added_keys = d2_keys - d1_keys
added_deltas = {o: (None, d2[o]) for o in added_keys}
deltas = {**shared_deltas, **added_deltas}
return parse_deltas(deltas)
def parse_deltas(deltas: dict) -> dict:
res = {}
for k, v in deltas.items():
if isinstance(v[0], dict):
tmp = diff_dict(v[0], v[1])
if tmp:
res[k] = tmp
else:
res[k] = v[1]
return res