-
-
Save onemach/2311470 to your computer and use it in GitHub Desktop.
JavaScript-like object in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class D(dict): | |
def __init__(self): | |
dict.__init__(self) | |
def __getitem__(self, key): | |
val = D() | |
try: | |
val = dict.__getitem__(self, key) | |
except: | |
dict.__setitem__(self, key, val) | |
return val | |
def __setitem__(self, key, val): | |
dict.__setitem__(self, key, val) | |
#I like JavaScript object. So I did this. | |
#try this | |
#> a = D() | |
#> a[1][2][3] = 4 |
@fajran yeah... I changed the name and forgot that. edited, thx
Have you tried using defaultdict?
from collections import defaultdict
D=lambda : defaultdict(D)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Isn't line 6 supposed to be
val = D()
?