Forked from jllopezpino/name_conventions_dictionaries.py
Last active
February 2, 2018 09:01
-
-
Save eriknguyen/b4f06f39f6430676de4de853d184d74e to your computer and use it in GitHub Desktop.
Replace keys in underscore lowercase convention for camel case convention and vice versa.
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 camel_to_underscore(name): | |
""" | |
Convert a name from camel case convention to underscore lower case convention. | |
Args: | |
name (str): name in camel case convention. | |
Returns: | |
name in underscore lowercase convention. | |
""" | |
camel_pat = compile(r'([A-Z])') | |
return camel_pat.sub(lambda x: '_' + x.group(1).lower(), name) | |
def underscore_to_camel(name): | |
""" | |
Convert a name from underscore lower case convention to camel case convention. | |
Args: | |
name (str): name in underscore lowercase convention. | |
Returns: | |
Name in camel case convention. | |
""" | |
under_pat = compile(r'_([a-z])') | |
return under_pat.sub(lambda x: x.group(1).upper(), name) | |
def change_dict_naming_convention(d, convert_function): | |
""" | |
Convert a nested dictionary from one convention to another. | |
Args: | |
d (dict): dictionary (nested or not) to be converted. | |
convert_function (func): function that takes the string in one convention and returns it in the other one. | |
Returns: | |
Dictionary with the new keys. | |
""" | |
if not (isinstance(dict_input, dict) or isinstance(dict_input, list)): | |
return dict_input | |
new = {} | |
for k, v in d.iteritems(): | |
new_v = v | |
if isinstance(v, dict): | |
new_v = change_dict_naming_convention(v, convert_function) | |
elif isinstance(v, list): | |
new_v = list() | |
for x in v: | |
new_v.append(change_dict_naming_convention(x, convert_function)) | |
new[convert_function(k)] = new_v | |
return new |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment