Created
November 12, 2015 09:47
-
-
Save jllopezpino/132a5cc45ea49f9f8106 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 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 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
I added this check for the case when a list inside that dictionary doesn't contain a dictionary but only number or string.