-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path42_flexible_dict.py
38 lines (29 loc) · 969 Bytes
/
42_flexible_dict.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
"""
In this exercise, we’ll also implement a subclass of dict, which I call
FlexibleDict. Dict keys are Python objects, and as such are identified with a
type. So if you use key 1 (an integer) to store a value, then you can’t use
key '1' (a string) to retrieve that value. But FlexibleDict will allow for
this. If it doesn’t find the user’s key, it will try to convert the key to
both str and int before giving up
"""
from collections import UserDict
class FlexibleDict(UserDict):
def __getitem__(self, key):
try:
if key in self:
pass
elif str(key) in self:
key = str(key)
elif int(key) in self:
key = int(k)
except ValueError:
pass
return UserDict.__getitem__(self, key)
d = {1: '1', 2: '2'}
fd = FlexibleDict()
fd['a'] = 100
print(fd['a'])
fd[5] = 500
print(fd[5])
fd['1'] = 100
print(fd[1])