Brain Goo

Carpe Crap ’em

Brain Goo header image 2

 

 

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

November 20th, 2014 · No Comments

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!

Tags: How Tos · Programming · python · Software

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment