Luiz
Luiz

Reputation: 67

KeyError in python…

I build a 3D array self.QL={} and "erase" the array with 0's:

for loop0 in range(50):
    for loop1 in range(50):
        for loop2 in range(self.actions):
            self.QL[loop0, loop1, loop2] = 0

But when I run the program and try to get a value from the array, it t hrows the error:

File "Bots/QL.py", line 135, in _chooseaction
self.vQ = self.QL[state[0],state[1],a]
KeyError: (0, 63, 0)

In line 135 I have:

def _chooseaction(self, state):
    self.vQ = 0
    self.action = 0
    self.temp = -1000

        for a in range(self.actions):
         self.vQ = self.QL[state[0],state[1],a]
           if self.vQ > self.temp:
             self.temp=self.vQ
             self.action=a

          return self.action

What did I do wrong?

Upvotes: 0

Views: 2241

Answers (1)

RemcoGerlich
RemcoGerlich

Reputation: 31260

state[1] has the value 63, but you only initialized it with values from 0 to 49.

Which is why it says that the key (0, 63, 0) doesn't exist.

Perhaps you can use a defaultdict?

from collections import defaultdict

self.QL = defaultdict(int)

Now self.QL is basically a dict that is 0 for any values it doesn't have.

Upvotes: 2

Related Questions