blog

rss

Key insensitive dictionary in Python

15/12/2009, 20h34

How nice looks a key case-insensitive dictionary written in Python:

class KeyInsensitiveDict:

def init(self, d={}): self.dict[“d”] = {} for k, v in d.items(): self[k] = v def getattr(self, attr): return getattr(self.dict[“d”], attr) def setattr(self, attr, value): setattr(self.dict[“d”], attr, value) def setitem(self, key, value): if (hasattr(key, “lower”)): key = key.lower() self.dict[“d”][key] = value def getitem(self, key): if (hasattr(key, “lower”)): key = key.lower() return self.dict[“d”][key]

Actually it’s just a simple usage of the decorator pattern. And I wrote this code because we need it for the Python SPARQL Wrapper.