user1473508 user1473508 - 3 months ago 15
Python Question

Python Update random field choice function from OrderedDict Class

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

changerandom
function in the
Greeting
class.

...[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


My code return the following:

Hi
Good morning!
Updated string: {'Good morning!': 'Hola!'}
Good morning!


While it should have returned:

Hi
Good morning!
Hola!


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!

Answer

The problem is that you're returning a result, without assigning it anywhere.

You also use the value of fields, rather than the key. So, your code should be something like

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

Note that we're using self.fields.update, and we're no longer returning anything.

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