python
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)
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'}
Was this helpful?
Similar Posts
- Convert all dictionary keys to uppercase in python
- Get all keys from a dictionary in Python
- Convert all string characters to lowercase in python
- [Python] Using comprehension expression to convert list of dictionaries to nested dictionary
- Convert pandas DataFrame to python collection - dictionary
- Convert a dictionary to pandas DataFrame in python
- Show all files in a dictionary as a list in Python