Search code snippets, questions, articles...

Convert all dictionary keys to lowercase in python

If you are using a dictionary in your Python code and the keys of the dictionary have uppercase letters and you want to convert the keys to lowercase then you can use the methods explained in this post.
# Define a dictionary
car = {
  "Modal": "X1s",
  "Showroom Address": "India",
  "Brand": "TATA",
  "Car Type": "Petrol"
}

# Convert dictionary keys to lowercase
car =  {key.lower(): val for key, val in car.items()}

# Print the result
print(car)
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.
Output
{'modal': 'X1s', 'showroom address': 'India', 'brand': 'TATA', 'car type': 'Petrol'}

In the above code snippet, we are using dict comprehension to convert all the keys of a dictionary(car) to lowercase letters. We are also using the lower() function of Python String to convert the key text to lowercase.

If you do not want to use dict comprehension then you can use the below code to convert dictionary keys to lowercase format.

car = {
  "Modal": "X1s",
  "Showroom Address": "India",
  "Brand": "TATA",
  "Car Type": "Petrol"
}

result = {}

for key, value in car.items():
    result[key.lower()] = value

# Print the result
print(result)

Output

{'modal': 'X1s', 'showroom address': 'India', 'brand': 'TATA', 'car type': 'Petrol'}

Convert dictionary keys to uppercase in Python

Was this helpful?
0 Comments