PYTHON
Building a Case-Insensitive Dictionary in Python
Create a custom case-insensitive dictionary in Python, ideal for storing and retrieving data regardless of key casing, perfect for user input, configuration settings, or HTTP headers in web apps.
class CaseInsensitiveDict(dict):
def __setitem__(self, key, value):
super().__setitem__(key.lower(), value)
def __getitem__(self, key):
return super().__getitem__(key.lower())
def __contains__(self, key):
return super().__contains__(key.lower())
def get(self, key, default=None):
return super().get(key.lower(), default)
def pop(self, key, default=None):
return super().pop(key.lower(), default)
# Example of how to handle keys() if needed
# For full dictionary-like behavior, more methods like .keys(), .items(), .values()
# would need careful implementation or overriding to return original case for keys,
# or consistently lowercased keys.
# For simplicity, this example focuses on get/set/contains.
# Example Usage
ci_dict = CaseInsensitiveDict()
ci_dict['Name'] = 'Alice'
ci_dict['AGE'] = 30
ci_dict['City'] = 'New York'
print(f"Value for 'name': {ci_dict['name']}")
print(f"Value for 'Age': {ci_dict.get('Age')}")
print(f"'city' in dict: {'city' in ci_dict}")
print(f"'COUNTRY' in dict: {'COUNTRY' in ci_dict}")
ci_dict['name'] = 'Bob' # Overwrites 'Name'
print(f"Updated value for 'name': {ci_dict['Name']}")
print(f"Internal dict representation (keys are lowercased): {ci_dict}")
How it works: This snippet shows how to create a CaseInsensitiveDict by subclassing Python's built-in dict and overriding key methods like __setitem__, __getitem__, __contains__, and get. All incoming keys are automatically converted to lowercase before storage or lookup, ensuring that data can be accessed regardless of the case used when specifying the key. This custom data structure is highly useful in web development for scenarios such as parsing HTTP headers, handling user input (e.g., configuration options, form fields), or storing environment variables where case variations should be ignored.