Make Python Dictionary keys Case insensitive – CaseInsensitiveDict
Today, I found a cool thing in Python. Actually, this function is a part of requests module. Using CaseInsensitiveDict of requests module, we can easily make our dictionary to be case insensitive.
Let’s understand this through an example.
myDict = {
"Name": "Saruk",
"Working-at": "codespeedy",
"Born-In": "India"
}
print(myDict["working-at"])If we run this we will get an error like this:
KeyError: 'working-at'
The reason is simple. We are trying to find the key “working-at” but our actual key is “Working-at”. The case is different.
So now we are going to fix it by using CaseInsensitiveDict
from requests.structures import CaseInsensitiveDict
myDict = {
"Name": "Saruk",
"Working-at": "codespeedy",
"Born-In": "India"
}
newDict =CaseInsensitiveDict(myDict)
print(newDict["working-at"])Output:
codespeedy
You can see there is no error anymore.
I thought it will be worth sharing with you and if you remeber this, it can be really helpful while working in Python projects with large dictionaries.
Leave a Reply