In [ ]:
In [1]:
class StrKeyDict0(dict):
def __missing__(self, key):
if isinstance(key, str):
raise KeyError(key)
return self[str(key)]
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def __contains__(self, key):
return key in self.keys() or str(key) in self.keys()
In [3]:
d = StrKeyDict0([('2', 'two'), ('4', 'four')])
In [4]:
d['2']
Out[4]:
In [5]:
d[4]
Out[5]:
In [6]:
d[1]
In [7]:
d['1']
In [8]:
d.get(2)
Out[8]:
In [9]:
d.get('2')
Out[9]:
In [10]:
d.get(1,'N/A')
Out[10]:
In [12]:
d.get('1', 'N/A')
Out[12]:
In [13]:
2 in d
Out[13]:
In [14]:
'2' in d
Out[14]:
In [15]:
import collections
In [16]:
class StrKeyDict(collections.UserDict):
def __missing__(self, key):
if isinstance(key, str):
raise KeyError(key)
return self[str(key)]
def __contains__(self, key):
return str(key) in self.data
def __setitem__(self, key, item):
self.data[str(key)] = item
In [18]:
d = StrKeyDict([(2, 'two'), ('4', 'four')])
In [19]:
sorted(d.keys())
Out[19]:
In [20]:
d[2], d['2']
Out[20]:
In [21]:
d[4], d['4']
Out[21]:
In [22]:
d['1']
In [23]:
d.get('2'), d.get('4')
Out[23]:
In [25]:
d.get(1, 'N/A'), d.get('1', 'N/A')
Out[25]:
In [ ]: