Forked from jllopezpino/name_conventions_dictionaries.py
Created
December 18, 2018 12:26
-
-
Save emamulandalib/29230431e04234220ac7cda353ea9440 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. | |
""" | |
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