Created
March 19, 2019 22:00
-
-
Save mikegrima/966effd21e61bd491c53739724057f8d to your computer and use it in GitHub Desktop.
Python snake_case to camelCase
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
def snake_to_camels(data: object) -> object: | |
"""Function that recursively converts snake_case to camelCase in a dict.""" | |
if isinstance(data, dict): | |
data_copy = dict(data) | |
for key, value in data.items(): | |
# Send the value back: | |
new_value = snake_to_camels(value) | |
# In case the key isn't a string (like an Int): | |
if isinstance(key, str): | |
text = key.split('_') | |
del data_copy[key] | |
data_copy[text[0] + ''.join(char.title() for char in text[1:])] = new_value | |
else: | |
data_copy[key] = new_value | |
return data_copy | |
elif isinstance(data, list): | |
return list(map(snake_to_camels, data)) | |
return data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment