让mydict [" foo / bar"]查找mydict [" foo"] [" bar"]

时间:2017-03-05 02:49:32

标签: python dictionary

我有一个嵌套的词典

root ={
  'user':{
    'Johnson':{
      'incoming':2000,
      'family'  :4,
      'play':None
    }
    'Smith':{
      'incoming':17000,
      'family'  :1,
      'play':False           
    }
  }
}

我可以访问任何记录,但只能使用大量语法:root['user']['Smith']['play']

我想以某种方式扩展语法,以便能够这样做:

print "Johnson incoming", root['/user/Johnson/incoming']
root['/user/Smith/play'] = True

区别于一些潜在的重复:

2 个答案:

答案 0 :(得分:4)

这样的事情怎么样:

class Foo(dict):
    def __setitem__(self, key, value):
        parts = key.split('/', 1)
        if len(parts) == 2:
            if parts[0] not in 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)
        if len(parts) == 2:
            return self[parts[0]][parts[1]]
        else:
            return super(Foo, self).__getitem__(key)

你可以像这样使用它:

In [8]: f = Foo()

In [9]: f['a/b/c'] = 10

In [10]: f['a/b/c']
Out[10]: 10

答案 1 :(得分:0)

root ={
  'user':{
    'Johnson':{
      'incoming':2000,
      'family'  :4,
      'play':None
    },
    'Smith':{
      'incoming':17000,
      'family'  :1,
      'play':False           
    }
  }
}


class myDict(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