Search code snippets, questions, articles...

Convert all dictionary keys to uppercase in python

You can use one of these methods to convert all the dictionary keys to uppercase format in Python.
# Define a dictionary
car = {
  "Modal": "X1s",
  "Showroom Address": "India",
  "Brand": "TATA",
  "Car Type": "Petrol"
}

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

# Print the result
print(car)
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool
Output
{'MODAL': 'X1s', 'SHOWROOM ADDRESS': 'India', 'BRAND': 'TATA', 'CAR TYPE': 'Petrol'}

We are using the upper() function of Python String along with dict comprehension to convert all the dictionary keys to UPPERCASE format in Python.

If you do not want to use dict comprehension then you can use the below code.

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

result = {}

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

print(result)

Output

{'MODAL': 'X1s', 'SHOWROOM ADDRESS': 'India', 'BRAND': 'TATA', 'CAR TYPE': 'Petrol'}

Convert dictionary keys to lowercase in Python

Was this helpful?
0 Comments