2017-08-24 84 views
1

我想通過它與一些值鍵SNMP OID和值字典字典的對象:如何獲得Python字典與SNMP OID關鍵

d = {'1.3.6.1.6.3.1.1.5.1': {'text':"something","help":'somethingelse','param':1}, 
    '1.3.6.1.6.3.1.1.5.2':{'text':"something for this oid","help":'somethingelse_for this','param':2} , 
    and so on for other 1000 snmp OIDs } 

現在我想通過這本字典轉換成字典對象並得到細節

class Struct(object): 
def __init__(self, adict): 
    """Convert a dictionary to a class 

    @param :adict Dictionary 
    """ 
    self.__dict__.update(adict) 
    for k, v in adict.items(): 
     if isinstance(v, dict): 
      self.__dict__[k] = Struct(v) 


s = Struct(d) 
s.? (what should be given here) 

什麼應該取代?作爲一個OID,我不能在引號(「」),因爲我需要傳遞屬性? 我得到無效的語法錯誤,如果我通過

s.'1.3.6.1.6.3.1.1.5.1' 
or 
s.1.3.6.1.6.3.1.1.5.1 

也說,經過OID屬性比如我s.some_oid會得到一個字典對象後,不知怎麼的,但我希望它返回OID的價值,以及作爲字典對象。可以做到嗎?

這意味着如果我通過s.some_oid我應該得到

{'text':"something","help":'somethingelse','param':1} 

而且其s.some_oid_text使用時Dictionary對象,我應該得到

something 

回答

1

您還沒有定義的GetItem功能爲你的班級。一旦你定義了它,你就可以像任何普通的字典一樣使用struct對象。此外,要將項目作爲Dictionary對象獲取,您還需要在Struct類本身中創建一個函數。爲了您的參考,我創建了函數'itemsAsDict()'。

d = {'1.3.6.1.6.3.1.1.5.1':{'text':"something","help":'somethingelse','param':1}} 

class Struct(object): 

    def __init__(self, adict): 
     """Convert a dictionary to a class 

     @param :adict Dictionary 
     """ 

     self.__dict__.update(adict) 

     for k, v in adict.items(): 
      if isinstance(v, dict): 
       self.__dict__[k] = Struct(v) 

    def __getitem__(self,key): 
     return self.__dict__[key] 

    def values(self): 
     return self.__dict__.values() 

    def itemsAsDict(self): 
     return dict(self.__dict__.items()) 


s = Struct(d) 


#Get the dictionary at OID 
print s['1.3.6.1.6.3.1.1.5.1'].itemsAsDict() 
##Output : {'text': 'something', 'help': 'somethingelse', 'param': 1} 

#Get the exact text 
print s['1.3.6.1.6.3.1.1.5.1']['text'] 
###Output : something 
+0

非常感謝你 – sans0909

+0

歡迎你:)如果我的回答對你有幫助,你可以請'接受'它。 –

+0

當然,謝謝 – sans0909