2

here's my code:

fList = {7:7, 9:9}

def checkList():
    if not None in fList:
        print(fList)
        fL = random.choice(fList)
        ttt[fL] = computerLetter
        del fList[fL]
        print(fL)
        print(ttt)
        print(fList)

Python throws me this error:

{9: 9, 7: 7}
Traceback (most recent call last):
  File "/home/jason/Desktop/Programming/Python3_5/TestCode.py", line 35,     in <module>
    checkList()
  File "/home/jason/Desktop/Programming/Python3_5/TestCode.py", line 22, in checkList
    fL = random.choice(fList)
  File "/usr/lib/python3.5/random.py", line 265, in choice
    return seq[i]
KeyError: 0

This was working fine when there were move key:value pairs in the dictionary. I'm having trouble understanding whats wrong. Thank you in advance for your time and attention.

1 Answer 1

3

From looking at your code it seems you expect random.choice to choose a key from you dictionary, so what you need to do is:

random.choice(list(fList.keys()))

BTW, I don't think you are using you conditional (if) properly. Currently it means that it will be executed only if fList doesn't have a key None (i.e. if your list was fList = {7:7, 9:9, None:5} it wouldn't execute). What I think you meant is if fList is not None, this means that it will only execute if it is defined

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. I want to run that if statement as long as the dictionary isn't empty. In your opinion what would be the best way of doing that?
The Pythonic way is to write if fList which evaluates to True when there are values inside the dictionary and False when it is empty. Since you're using a dictionary, why are you calling it a fList?
No real reason. I just decided on a name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.