简体   繁体   English

将同一类的对象放入具有不同键Python的字典中

[英]Putting objects of the same class into a dictionary with different keys Python

I have these Objects: 我有这些物品:

class Object(object):

    def __init__(self, name, *parameters):
        self.name = name
        self.parameters = parameters

    def name(self):
        return self.name

    def parameters(self):
        return self.parameters

class Parameter(object):

    def __init__(self, name, value):
        self.name = name
        self.value = value

My aim is to get all parameters of 1 object in a dictionary, but it needs to end up like this: 我的目标是在字典中获取1个对象的所有参数,但它需要像这样结束:

{ParameterOne: "ValueOne", ParameterTwo: "ValueTwo"}

Since I have to be able to give the parameters different names, I can't do it like this: 既然我必须能够为参数赋予不同的名称,我不能这样做:

class Parameter(object):

    def __init__(self, value):
        self.ParameterOne = value

I tried it like this which obviously didn't work: 我试过这样的事情显然不起作用:

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

Is there any way to achieve this? 有没有办法实现这个目标?

data = {parameter: ''.join(['Value ', str(index)]) 
         for index, parameter in enumerate(object.parameters)}

This will give you {parameter0: 'Value 0', ...} If you want to get the English words for the numbers, you;ll have to either roll your own function for it or use an external package like inflect . 这将为您提供{parameter0: 'Value 0', ...}如果您想获取数字的英文单词,您必须为其滚动自己的函数或使用像inflect这样的外部包。

Just an observation, but most dictionaries would have the string mapping to the object, not the other way around. 只是观察,但大多数词典都会将字符串映射到对象,而不是相反。 Is there some reason you're doing it this way? 你有这样做的原因吗?

EDIT: 编辑:

Rereading your question, are you looking for 重读你的问题,你在寻找吗?

data = {parameter: parameter.name for parameter in object.parameters}

I think you might want to try instead 我想你可能想尝试一下

data = {parameter.name: parameter.value for parameter in object.parameters}

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

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