Last active
January 30, 2020 02:35
-
-
Save kognate/c18658d36acc4143553d0df2eba39003 to your computer and use it in GitHub Desktop.
dict reformulator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Dict, List | |
from itertools import chain | |
to_convert = { | |
"someCommonKey": 123, | |
"listOne": ["foo", "bar", "baz"], | |
"listTwo": ["lorem", "ipsum", "doler"], | |
"listThree": ["jorem", "jpsum", "joler"], | |
} | |
ignore = ["someCommonKey"] | |
def reformulator(source_dict: Dict, ignore_keys: List[str]) -> Dict: | |
if len(set(ignore_keys)) != len(ignore_keys): | |
raise ValueError("Duplicate Keys are not allowed") | |
key_count = len(set(to_convert.keys() - ignore_keys)) | |
intermediate_res = list( | |
chain.from_iterable( | |
[ | |
list(zip([k for _ in range(0, len(v))], v)) | |
for k, v in source_dict.items() | |
if k not in ignore | |
] | |
) | |
) | |
final_result = {ik: source_dict[ik] for ik in ignore_keys} | |
final_result["children"] = [ | |
dict(intermediate_res[n::key_count]) for n in range(0, key_count) | |
] | |
return final_result | |
expected_result = { | |
"someCommonKey": 123, | |
"children": [ | |
{"listOne": "foo", "listTwo": "lorem", "listThree": "jorem"}, | |
{"listOne": "bar", "listTwo": "ipsum", "listThree": "jpsum"}, | |
{"listOne": "baz", "listTwo": "doler", "listThree": "joler"}, | |
], | |
} | |
assert expected_result == reformulator(to_convert, ignore) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment