Created
October 8, 2018 12:50
-
-
Save marteinn/00a478d96ad78cb88224d9a98418b03d to your computer and use it in GitHub Desktop.
A helper for converting dictionary keys between camel and snake case
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 re | |
def snake_case_to_camel_case(val): | |
return converter(val, snake_case_to_camel_case, snake_to_camel) | |
def camel_case_to_snake_case(val): | |
return converter(val, camel_case_to_snake_case, camel_to_snake) | |
def converter(val, dict_method, str_method): | |
return { | |
str_method(k): | |
converter(v, dict_method, str_method) if isinstance(v, dict) else v | |
for (k, v) in val.items() | |
} | |
def snake_to_camel(text): | |
return re.sub('_([a-zA-Z0-9])', lambda m: m.group(1).upper(), text) | |
def camel_to_snake(text): | |
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text) | |
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment