Hello my name is Mikal.

I am working on some python code, and it is now at the point where it does what I want, but its not quite fast enough for my liking.

Here is my current code that works:

self.timersVS = {'combat':0,'regen':0}

        ...

            # Tick Timers and clamp
            for key,value in self.timersVS.iteritems():
                if value <= 1:
                    self.timersVS[key] = 0
                    continue
                else:
                    self.timersVS[key] -= 1

Is the following code the same, and is there any improvement over using it? Is there a more efficient way of writing this functionallity?

self.timersVS = {'combat':0,'regen':0}

        ...

            # Tick Timers and clamp
            self.timersVS = [x - 1 for x in self.timersVS if x]

Thank you so much!
-Mikal

The result of the list comprehension you showed will be a list, not a dictionary.

The result of the list comprehension you showed will be a list, not a dictionary.

Yeah, I realized after I posted that my second code there is wrong.

But is there a more efficient way of decrementing a dictionary's values by 1 until they reach 0?

for key,value in self.timersVS.iteritems():
                if value:
                    self.timersVS[key] -= 1

Is this a little better?

-Mikal

It's simpler, easier to read and maintain. If you use for key, value in timersVS.items():, you can use it with Python2 and Python3.

It's simpler, easier to read and maintain. If you use for key, value in timersVS.items():, you can use it with Python2 and Python3.

Ok thanks! So theres no more efficent way? I just want to make sure so I can move on to the next bit of code.

-Mikal

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.