Created
December 15, 2022 11:36
-
-
Save arnos-stuff/69f5b1626d910d78c8eb53eecc131410 to your computer and use it in GitHub Desktop.
flatten a dict baseline (should remove class method)
This file contains 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
def flatten(cls, obj): | |
if isinstance(obj, (str, int, float)): | |
return obj | |
elif isinstance(obj, list): | |
return [cls.flatten(item) for item in obj] | |
elif isinstance(obj, dict): | |
flatobj = {} | |
for key, val in obj.items(): | |
if isinstance(val, list): | |
for i, item in enumerate(val): | |
if not isinstance(item, dict): | |
flatobj[key + '.i' + str(i)] = cls.flatten(item) | |
else: | |
for subkey, subval in cls.flatten(item).items(): | |
flatobj[key + '.i' + str(i) + '.' + subkey] = subval | |
elif not isinstance(val, dict): | |
flatobj[key] = cls.flatten(val) | |
else: | |
for subkey, subval in cls.flatten(val).items(): | |
flatobj[key + '.' + subkey] = subval | |
return flatobj |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment