Python Update random field choice function from OrderedDict Class
<p>I'm trying to do a script that choose a string and update a current field, but for some reason the code doesn't update the last value when calling my <code>changerandom</code> function in the <code>Greeting</code> class.</p>

<pre><code>...[snip]...
class Greeting(Packet):
    fields = OrderedDict([
         ("Morning",     "Hi"),
         ("Afternoon",   "Good Afternoon!"),
         ("Evening",     "Good Evening!"),
    ])

    def change(self):
        self.fields["Morning"] = "Good morning!"

    def changerandom(self, n = 1): 
        function=[
                    {self.fields["Morning"]: "Hello!"},
                    {self.fields["Morning"]: "Bonjorno!"},
                    {self.fields["Morning"]: "Hola!"},
                 ]
        result = {}
        for i in range(n):
            result.update(choice(function))
            print "Updated string:",result
            return result
text = Greeting()
print text
text.change()
print text
text.changerandom()
print text
</code></pre>

<p>My code return the following:</p>

<pre><code>Hi
Good morning!
Updated string: {'Good morning!': 'Hola!'}
Good morning!
</code></pre>

<p>While it should have returned:</p>

<pre><code>Hi
Good morning!
Hola!
</code></pre>

<p>I'm not sure what i'm missing here, I don't see why I cannot update the last field. 
Any help would be greatly appreciated!</p>

<p>The problem is that you're <code>return</code>ing a result, without assigning it anywhere.</p>

<p>You also use the <em>value</em> of <code>fields</code>, rather than the <em>key</em>.  So, your code should be something like </p>

<pre><code>def changerandom(self, n = 1): 
        function=[
                    {"Morning": "Hello!"},
                    {"Morning": "Bonjorno!"},
                    {"Morning": "Hola!"},
                 ]

        for i in range(n):
            result = choice(function)
            self.fields.update(result)
            print "Updated string:",result
            return result
</code></pre>

<p>Note that we're using <code>self.fields.update</code>, and we're no longer <code>return</code>ing anything.</p>

<p>Generally, it's good practice for your functions and methods to <em>return</em> something, or <em>change something</em>, but never both.</p>

python string function