
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert Python dictionary keys/values to lowercase?
Python Dictionaries
A dictionary in Python is a collection of key-value pairs. Each key is unique and maps to a specific value. For example-
{"Title": "The Hobbit", "Author":"J.R.R. Tolkien", "Year": 1937}
Dictionaries don't use numeric indexes and don't maintain a fixed order. We can't insert items in a specified position, as dictionaries store data based on keys, other than sequences. Where values can be strings, numbers, or float, and keys can be strings, numbers, or tuples.
Lowercasing Python Dictionary Keys and Values
To convert dictionary keys and values to lowercase in Python, we can loop through the dictionary and create a new one with updated entries. This ensures all keys and values are in lowercase while maintaining their original mappings.
def lower_dict(d): new_dict = dict((k.lower(), v.lower()) for k, v in d.items()) return new_dict a = {'Foo': "Hello", 'Bar': "World"} print(lower_dict(a))
The result is produced as follows -
{'foo': 'hello', 'bar': 'world'}
Example
We need to convert the dictionary keys to lowercase in Python, we can apply the .lower() function to each key while keeping the values unchanged. This means we can create a new dictionary where all the keys are in lowercase but the values remain the same.
def lower_dict(d): new_dict = dict((k.lower(), v) for k, v in d.items()) return new_dict a = {'Foo': "Hello", 'Bar': "World"} print(lower_dict(a))
The result is obtained as follows -
{'foo': 'Hello', 'bar': 'World'}
Example
This code uses a dictionary comprehension to change all the keys in a dictionary to lowercase. This goes through each key-value in original_dict, changes the key to lowercase using the .lower() method, and stores it in a new dictionary called new_dict. Here, the values remain unchanged.
original_dict = {'Name': 'sai', 'AGE': 25, 'coUNTry': 'America'} new_dict = {s.lower(): a for s, a in original_dict.items()} print(new_dict)
We will get the output as follows -
{'name': 'sai', 'age': 25, 'country': 'America'}