Making Mydict["foo/bar"] Look Up Mydict["foo"]["bar"]
I have a nested dictionaries root ={ 'user':{ 'Johnson':{ 'incoming':2000, 'family' :4, 'play':None } 'Smith':{ 'incoming':17000, 'fami
Solution 1:
How about something like this:
classFoo(dict):
def__setitem__(self, key, value):
parts = key.split('/', 1)
iflen(parts) == 2:
if parts[0] notin self:
self[parts[0]] = Foo()
self[parts[0]].__setitem__(parts[1], value)
else:
super(Foo, self).__setitem__(key, value)
def__getitem__(self, key):
parts = key.split('/', 1)
iflen(parts) == 2:
return self[parts[0]][parts[1]]
else:
returnsuper(Foo, self).__getitem__(key)
You can use it like this:
In [8]: f = Foo()
In [9]: f['a/b/c'] = 10
In [10]: f['a/b/c']
Out[10]: 10
Solution 2:
root ={
'user':{
'Johnson':{
'incoming':2000,
'family' :4,
'play':None
},
'Smith':{
'incoming':17000,
'family' :1,
'play':False
}
}
}
classmyDict(dict):
'my customer dictionary'def__setitem__(self, key, val):
_, first, second, third = key.split('/')
print first, second, third
firstDict = self[first]
secondDict = firstDict[second]
dict.__setitem__(secondDict, third, val)
a = myDict(root)
print a
a['/user/Smith/play'] = 'hi there'print a
Post a Comment for "Making Mydict["foo/bar"] Look Up Mydict["foo"]["bar"]"