DeaD_EyE

CaseInsensitiveDict

Jun 28th, 2022 (edited)
174
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from collections import UserDict
  2.  
  3.  
  4. class CaseInsensitiveDict(UserDict):
  5.     def __init__(self, iterable=None, **mapping):
  6.         iterable = iterable or []
  7.        
  8.         if isinstance(iterable, dict):
  9.             iterator = iterable.items()
  10.         else:
  11.             iterator = iterable
  12.            
  13.         items = {k.casefold(): v for k, v in iterator}
  14.         super().__init__(items, **mapping)
  15.  
  16.  
  17.     def __getitem__(self, key):
  18.         return super().__getitem__(key.casefold())
  19.  
  20.     def __setitem__(self, key, value):
  21.         super().__setitem__(key.casefold(), value)
  22.  
  23.     def __contains__(self, key):
  24.         return super().__contains__(key.casefold())
  25.  
  26.     def get(self, key, default=None):
  27.         key = key.casefold()
  28.         if key in self:
  29.             return super().__getitem__(key)
  30.         else:
  31.             return default
  32.  
  33.     def has_key(self, key):
  34.         return key.casefold() in self
  35.  
  36.     def pop(self, key, default=None):
  37.         key = key.casefold()
  38.         if key in self:
  39.             return super().pop(key)
  40.         else:
  41.             return default
  42.  
  43.     def setdefault(self, *args, **kwargs):
  44.         raise NotImplementedError
  45.  
  46.  
  47. data = CaseInsensitiveDict({"A": 42, "b": 1337}, C=44)
  48. print(data)
  49. print(data["a"])
  50. print(data["A"])
  51. print(data["b"])
  52. print(data["B"])
  53. print(data.get("C", "MISSING"))
  54. print(data.get("A", "MISSING"))
  55. print(data.pop("A"))
  56. print(data)
  57. print(data.pop("B"))
RAW Paste Data Copied