Last active
June 18, 2022 18:04
-
-
Save JokerMartini/c3a38069020480727e5e to your computer and use it in GitHub Desktop.
Python: Renames recursively every key in a dictionary to lowercase.
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
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 |
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@bahamut45 If you really want to recursively, I think this would be the way: