简体   繁体   English

Python将多个对象变成字典

[英]Python turning multiple objects into a dictionary

I've got an Object which has a name and an indefinite amount of parameters (which is also an object with a name and a value) 我有一个具有名称和不确定数量的参数的对象(这也是具有名称和值的对象)

I'm pretty new to python so this gets a bit over my head I want to get all parameters and put them into a dictionary. 我是python的新手,所以这有点烦人,我想获取所有参数并将它们放入字典中。 My code looks like this: 我的代码如下所示:

data = {}

for parameter in object.parameters:
    parameter.__dict__
    data.update({parameter})

But parameter.__dict__ doesn't work like I thought here. 但是parameter .__ dict__不能像我在这里想的那样工作。 Any ideas how i can make it work? 有什么想法我可以使它工作吗?

EDIT: Thanks it worked by using data.update(vars(parameter)) 编辑:感谢使用data.update(vars(parameter))的工作

By looking at your output it looks like you class structure is something like this 通过查看您的输出,看起来您的类结构是这样的

class class1(object):
    def __init__(self, p1, p2):
        self.name =  p1
        self.value = p2

class class2(object):
    def __init__(self):
        self.parameters = [class1("param1", "value1"), class1("param2", "value2")]


obj = class2()

data = {}

So when we do 所以当我们这样做

for parameter in obj.parameters:
    print(parameter.__dict__)

We get output 我们得到输出

{'value': 'value1', 'name': 'param1'}
{'value': 'value2', 'name': 'param2'}

So to get the desired output you will have to do something like 因此,要获得所需的输出,您将必须执行以下操作

for parameter in obj.parameters:
    data[parameter.__dict__['name']] = parameter.__dict__['value']

print(data)

Which will give your desired output 这将给您想要的输出

{'param2': 'value2', 'param1': 'value1'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM