Ignoring case-sensitivity in Dictionary Keys When Printing in Python

AuthorSumit Dey Sarkar

Pubish Date02 May 2023

categoryPython

In this tutorial we will learn how to ignore case-sensitivity in Python dictionary keys when printing to a string, console, or file using dictionary comprehension.

 

Ignoring case-sensitivity in Dictionary Keys When Printing in Python

 

Ignoring case-sensitivity in dictionary keys when printing in Python

To ignore case-sensitivity in dictionary keys when printing the dictionary to a string, console, or file in Python, you can convert the keys to lowercase or uppercase using a dictionary comprehension.

 

Here's an example:

 

my_dict = {'Apple': 3, 'Banana': 5, 'Orange': 2}

# Convert the keys to lowercase
lower_dict = {k.lower(): v for k, v in my_dict.items()}

# Print the lowercase dictionary
print(lower_dict)

# Convert the keys to uppercase
upper_dict = {k.upper(): v for k, v in my_dict.items()}

# Print the uppercase dictionary
print(upper_dict)

 

Output

{'apple': 3, 'banana': 5, 'orange': 2}

 

{'APPLE': 3, 'BANANA': 5, 'ORANGE': 2}

 

Note- Depending on your needs, you may then use the lowercase or uppercase dictionary to print to a string, console, or file.

Comments 0

Leave a comment