Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import UserDict
- class CaseInsensitiveDict(UserDict):
- def __init__(self, iterable=None, **mapping):
- iterable = iterable or []
- if isinstance(iterable, dict):
- iterator = iterable.items()
- else:
- iterator = iterable
- items = {k.casefold(): v for k, v in iterator}
- super().__init__(items, **mapping)
- def __getitem__(self, key):
- return super().__getitem__(key.casefold())
- def __setitem__(self, key, value):
- super().__setitem__(key.casefold(), value)
- def __contains__(self, key):
- return super().__contains__(key.casefold())
- def get(self, key, default=None):
- key = key.casefold()
- if key in self:
- return super().__getitem__(key)
- else:
- return default
- def has_key(self, key):
- return key.casefold() in self
- def pop(self, key, default=None):
- key = key.casefold()
- if key in self:
- return super().pop(key)
- else:
- return default
- def setdefault(self, *args, **kwargs):
- raise NotImplementedError
- data = CaseInsensitiveDict({"A": 42, "b": 1337}, C=44)
- print(data)
- print(data["a"])
- print(data["A"])
- print(data["b"])
- print(data["B"])
- print(data.get("C", "MISSING"))
- print(data.get("A", "MISSING"))
- print(data.pop("A"))
- print(data)
- print(data.pop("B"))
Add Comment
Please, Sign In to add comment