python - 如何以 snmp OID 作为键获取 python 字典作为对象

标签 python class dictionary

我正在尝试传递一个字典,其中键为 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 时我应该得到

something

最佳答案

您还没有为您的类定义getitem函数。一旦定义了它,就可以像任何普通字典一样使用结构对象。此外,要以 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

关于python - 如何以 snmp OID 作为键获取 python 字典作为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45853579/

相关文章:

c# - 如何制作一个具有多个键和廉价的 Contains 操作的字典?

arrays - 配置单元从两个数组创建映射或键/值对

python - 删除 None 值的管道

在 Rails 上运行 Python?

c++ - 仅对一个成员使用 C++ 访问修饰符

java:用==或.equals()比较类:有区别吗?

java - 从 JAR 加载类时出现 ClassNotFoundException

python - 比较嵌套字典列表中的项目并执行简单的算术运算

python - 如何将 JPEG 图像插入 python Tkinter 窗口?

python - 以与使用元组相同的方式使用 ndarray 进行索引