Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to convert Python dictionary keys/values to lowercase?
A dictionary in Python is a collection of key-value pairs where each key is unique and maps to a specific value. Sometimes you need to convert dictionary keys or values to lowercase for consistency or comparison purposes.
Converting Both Keys and Values to Lowercase
To convert both dictionary keys and values to lowercase, you can use dictionary comprehension with the lower() method ?
def lower_dict(d):
new_dict = dict((k.lower(), v.lower()) for k, v in d.items())
return new_dict
original = {'Foo': "Hello", 'Bar': "World"}
result = lower_dict(original)
print(result)
{'foo': 'hello', 'bar': 'world'}
Converting Only Keys to Lowercase
When you need to convert only the keys to lowercase while keeping values unchanged ?
def lower_keys(d):
new_dict = dict((k.lower(), v) for k, v in d.items())
return new_dict
original = {'Foo': "Hello", 'Bar': "World"}
result = lower_keys(original)
print(result)
{'foo': 'Hello', 'bar': 'World'}
Using Dictionary Comprehension
Dictionary comprehension provides a more concise way to convert keys to lowercase ?
original_dict = {'Name': 'sai', 'AGE': 25, 'coUNTry': 'America'}
new_dict = {key.lower(): value for key, value in original_dict.items()}
print(new_dict)
{'name': 'sai', 'age': 25, 'country': 'America'}
Converting Only Values to Lowercase
To convert only string values to lowercase while preserving keys ?
original = {'Name': 'ALICE', 'City': 'NEW YORK', 'Age': 30}
new_dict = {key: value.lower() if isinstance(value, str) else value
for key, value in original.items()}
print(new_dict)
{'Name': 'alice', 'City': 'new york', 'Age': 30}
Comparison of Methods
| Method | Keys | Values | Best For |
|---|---|---|---|
| Dictionary Comprehension | Converted | Optional | Most readable |
| Generator Expression | Converted | Optional | Memory efficient |
| Loop with isinstance() | Optional | String only | Mixed data types |
Conclusion
Use dictionary comprehension for converting dictionary keys to lowercase as it's the most readable approach. When dealing with mixed data types, check with isinstance() to avoid errors on non-string values.
