Search code examples
pythonjsondictionarylowercase

How to lowercase all keys in json dict with Python


I am new to this site so be gentle to me, no homo.

I'm currently practicing my Python skills with code that checks given key against JSON dictionary and gives you the definition of key. Now I know there are other solutions to my issue, but I'm trying to figure out this one specifically if it's possible.

I'm trying to change all keys in my dictionary to lowercase, and I'm trying it like this for now:

data = json.load(open("data.json"))

for key in data.keys():
    key = key.lower()

What this dictionary file looks like (example of one key):

"act": ["Something done voluntarily by a person, and of such a nature that certain legal consequences attach to it.", "Legal documents, decrees, edicts, laws, judgments, etc.", "To do something.", "To perform a theatrical role."]

Apparently it has more than one value per key which creates problem when trying other solutions.


Solution

  • You can try this,

    data = json.load(open("data.json"))
    new_data = {key.lower():value for key, value in data.items()}
    

    And then you can replace the old data with the new one.

    with open("data.json") as fp:
        json.dump(new_data, fp)