Skip to content

Instantly share code, notes, and snippets.

@JokerMartini
Last active June 18, 2022 18:04
Show Gist options
  • Save JokerMartini/c3a38069020480727e5e to your computer and use it in GitHub Desktop.
Save JokerMartini/c3a38069020480727e5e to your computer and use it in GitHub Desktop.
Python: Renames recursively every key in a dictionary to lowercase.
import sys
data = {
'MIKE' : ['Great'],
'SUE' : ['happy'],
'JAN' : ['sad']
}
for k, v in data.items():
print k, v
def renameKey(iterable, oldkey, newKey):
if type(iterable) is dict:
for key in iterable.keys():
if key == oldkey:
iterable[newKey] = iterable.pop(key)
return iterable
data = renameKey(data, 'MIKE', 'JokerMartini')
for k, v in data.items():
print k, v
import sys
data = {
'MIKE' : ['Great'],
'SUE' : ['happy'],
'JAN' : ['sad']
}
for k, v in data.items():
print k, v
def renameKeysToLower(iterable):
if type(iterable) is dict:
for key in iterable.keys():
iterable[key.lower()] = iterable.pop(key)
if type(iterable[key.lower()]) is dict or type(iterable[key.lower()]) is list:
iterable[key.lower()] = renameKeysToLower(iterable[key.lower()])
elif type(iterable) is list:
for item in iterable:
item = renameKeysToLower(item)
return iterable
data = renameKeysToLower(data)
for k, v in data.items():
print k, v
@hunkim
Copy link

hunkim commented Jun 18, 2022

@bahamut45 If you really want to recursively, I think this would be the way:

def dict_rename_key(iterable, old_key, new_key):
    """
    dict_rename_key method

    Args:
        iterable (dict): [description]
        old_key (string): [description]
        new_key (string): [description]

    Returns:
        dict: [description]

    Examples:

    >>> data = {'MIKE': 'test', 'JOHN': 'doe'}
    >>> data_modified = dict_rename_key(data, 'MIKE', 'mike')
    >>> assert 'mike' in data_modified

    """
    if isinstance(iterable, dict):
        for key in list(iterable.keys()):
            if key == old_key:
                iterable[new_key] = dict_rename_key(iterable.pop(key), old_key, new_key)
            else:
                iterable[key] = dict_rename_key(iterable.pop(key), old_key, new_key)
    return iterable

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