def test_flatten_dict(self): self.assertEqual( sorted(h.flatten_dict( {"a": {"c": 1, "d": 2}, "b": {"c": 10, "d": 11, "e": 12}, "c": 20})), [(("a", "c"), 1), (("a", "d"), 2), (("b", "c"), 10), (("b", "d"), 11), (("b", "e"), 12), (("c", ), 20)])
def get_flattened(dct, names, path_joiner="_"): """Flatten a child dicts, whose resulting keys are joined by path_joiner. E.G. { "valuation": { "currency": "USD", "amount": "100" } } -> { "valuation_currency": "USD", "valuation_amount": "100" } """ new_dct = dict() for key, val in dct.items(): if key in names: child = {path_joiner.join(k): v for k, v in flatten_dict(val, (key, ))} new_dct.update(child) else: new_dct[key] = dct[key] return new_dct