Skip to content

Instantly share code, notes, and snippets.

@jllopezpino
Created November 12, 2015 09:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jllopezpino/132a5cc45ea49f9f8106 to your computer and use it in GitHub Desktop.
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.
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
@eriknguyen
Copy link

eriknguyen commented Feb 2, 2018

I added this check for the case when a list inside that dictionary doesn't contain a dictionary but only number or string.

if not (isinstance(d, dict) or isinstance(d, list)):
    return dict_input

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment