Last active
March 4, 2026 15:17
-
-
Save glauesppen/39c8e46288d8591667303bebd537673e to your computer and use it in GitHub Desktop.
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
| import unittest | |
| def flatten_object(example, parent_key='', sep='.'): | |
| expected = {} | |
| for x, y in example.items(): | |
| # Create the new key by appending the current key to the parent key | |
| if parent_key: | |
| # I need the key to be a string | |
| # where parent_key is the previous key | |
| # sep is the separator "." | |
| # and x is the next interation | |
| new_key = f"{parent_key}{sep}{x}" | |
| else: | |
| # If there are no parent_key, then the first key is x | |
| new_key = x | |
| # Here I am checking if the nested value is a dictionary, if it is, | |
| # I will go inside of it and recursively call the function again | |
| # Ref: https://www.w3schools.com/python/ref_func_isinstance.asp | |
| if isinstance(y, dict): | |
| # Since Peter gave me a hint to use the recursive function, | |
| # I will use it to update the items dictionary with the flattened nested dictionary | |
| # https://www.w3schools.com/python/ref_dictionary_update.asp | |
| expected.update(flatten_object(y, new_key, sep=sep)) | |
| else: | |
| expected[new_key] = y | |
| return expected | |
| example = { | |
| "a": { | |
| "b": { | |
| "c": 1, | |
| "f": 2, | |
| }, | |
| "g": 3, | |
| }, | |
| "d": 2, | |
| } | |
| expected = { | |
| "a.b.c": 1, | |
| "a.b.f": 2, | |
| "a.g": 3, | |
| "d": 2, | |
| } | |
| class TestFlattenMethods(unittest.TestCase): | |
| def test_flatten(self): | |
| result = flatten_object(example) | |
| self.assertDictEqual(result, expected) | |
| if __name__ == "__main__": | |
| # Note: If running in an interactive environment like a Jupyter notebook, | |
| # use unittest.main(argv=['first-arg-is-ignored'], exit=False) | |
| unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment