Putting objects of the same class into a dictionary with different keys Python
<p>I have these Objects:</p>

<pre><code>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
</code></pre>

<p>My aim is to get all parameters of 1 object in a dictionary, but it needs to end up like this:</p>

<pre><code>{ParameterOne: "ValueOne", ParameterTwo: "ValueTwo"}
</code></pre>

<p>Since I have to be able to give the parameters different names, I can't do it like this:</p>

<pre><code>class Parameter(object):

    def __init__(self, value):
        self.ParameterOne = value
</code></pre>

<p>I tried it like this which obviously didn't work:</p>

<pre><code>data = {}
    for parameter in object.parameters:
        data.update(vars(parameter))
</code></pre>

<p>Is there any way to achieve this?</p>

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

<p>This will give you <code>{parameter0: 'Value 0', ...}</code>  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 <code>inflect</code>.</p>

<p>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?</p>

<p>EDIT:</p>

<p>Rereading your question, are you looking for </p>

<pre><code>data = {parameter: parameter.name for parameter in object.parameters}
</code></pre>

<p>I think you might want to try instead</p>

<pre><code>data = {parameter.name: parameter.value for parameter in object.parameters}
</code></pre>

python dictionary