HOW TO Lower Case All Dictionary Keys in a Complex Python Dictionary

This tutorial shows you how to write and use a function that will iterate over complex, nested dictionary or list or combination of the two. For any dictionaries it finds, it will rename the keys to lower-case.

This is useful when trying to match an known string with a key name returned from another source where the characters are correct, but may come back in camelCase or in the wrong or just unknown case.

First: Write the function.
def renameKeys(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()] = renameKeys(iterable[key.lower()])
    elif type(iterable) is list:
        for item in iterable:
            item = renameKeys(item)
    return iterable

Next, create some sort of test list:
somelist = [
  {
  'myKey': 'asdA',
  'ASDFASDurKey':
    [
      {'QDD' : 'booger'},
      'asdf',
      [1,2]
    ]
  }
]

Finally call it:
somelist = renameKeys(somelist)

CAUTION: If your dictionary has two elements with the same ascii characters in two separate cases such as mydict[‘key1’] and mydict[‘KEY1’], the function works on a last-match basis. That means whichever dictionary element gets renamed last wins.

Did you find this post useful or have questions or comments? Please let me know!

This entry was posted in How Tos, Programming, python, Software. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *