Skip to content

Instantly share code, notes, and snippets.

@mikegrima
Created March 19, 2019 22:00
Show Gist options
  • Save mikegrima/966effd21e61bd491c53739724057f8d to your computer and use it in GitHub Desktop.
Save mikegrima/966effd21e61bd491c53739724057f8d to your computer and use it in GitHub Desktop.
Python snake_case to camelCase
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