Search code examples
pythonpython-3.xkeyerror

Getting a key error while appending lists to dictionary values


I have the following code:

import random

dic = {2:[],4:[]}
lis = []

# Create a random dataset of 10 lists
for number in range(0,10):
    # Each list consists of 8 random numbers ...
    lis.append(random.sample(range(0,9),8))
    # ... followed by a 2 or 4, corresponding to dic keys
    lis[-1].append(random.randint(2,4))

# Iterate through lis. Append sublists to dic values, using key per
# last item of sublist, 2 or 4. Strip the key itself.

for i in lis:
    dic[i[-1]].append(i[:-1])    # <----- getting a key error here

# End result should be dic looking like this (shortened):
# dic = {2:[[1,2,5,0,8],[0,4,2,8,3]],4:[[6,2,3,6,2],[2,2,3,1,3]]}

As shown in the comment, I am getting a key error when I try to append the sublist to the value within dic. Can’t figure out why. Help?


Solution

  • Being unfamiliar with your problem domain, I don’t understand the rationale behind this code. However, I’ve run it with print calls added to show what was going on (a valuable debugging technique I recommend to you), and the problem is here:

    lis[-1].append(random.randint(2,4))
    

    randint(2,4) returns a random integer between 2 and 4, including 3. When subsequent code hits a 3, you get a key error. Instead, the line should use something like:

    lis[-1].append(random.choice((2, 4)))