![]() |
why is this dictionary giving a Keyerror? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: why is this dictionary giving a Keyerror? (/thread-23112.html) |
why is this dictionary giving a Keyerror? - philipbergwerf - Dec-11-2019 Hello I have a question, I don't understand why the following code gives a Keyerror because google says "What a Python KeyError Usually Means. A Python KeyError exception is what is raised when you try to access a key that isn't in a dictionary ( dict )." the numbers from right_hand_numbers are in the list for sure: from tkinter import * from tkinter import messagebox root: Tk = Tk() root.title('PianoScript® Diagram') root.geometry("480x85+300+400") frame: Frame = Frame(root, bg='white') frame.pack() diagramCanvas = Canvas(frame, width=480, height=50) diagramCanvas.pack(side=BOTTOM) def write_cross_hands_dot(): right_hand_numbers = [40, 44, 56] dotYposition = {'1': 10, '2': 27, '3': 10, '4': 10, '5': 27, '6': 10, '7': 27, '8': 10, '9': 10, '10': 27, '11': 10, '12': 27, '13': 10, '14': 27, '15': 10, '16': 10, '17': 27, '18': 10, '19': 27, '20': 10, '21': 10, '22': 27, '23': 10, '24': 27, '25': 10, '26': 27, '27': 10, '28': 10, '29': 27, '30': 10, '31': 27, '32': 10, '33': 10, '34': 27, '35': 10, '36': 27, '37': 10, '38': 27, '39': 10, '40': 10, '41': 27, '42': 10, '43': 27, '44': 10, '45': 10, '46': 27, '47': 10, '48': 27, '49': 10, '50': 27, '51': 10, '52': 10, '53': 27, '54': 10, '55': 27, '56': 10, '57': 10, '58': 27, '59': 10, '60': 27, '61': 10, '62': 27, '63': 10, '64': 10, '65': 27, '66': 10, '67': 27, '68': 10, '69': 10, '70': 27, '71': 10, '72': 27, '73': 10, '74': 27, '75': 10, '76': 10, '77': 27, '78': 10, '79': 27, '80': 10, '81': 10, '82': 27, '83': 10, '84': 27, '85': 10, '86': 27, '87': 10, '88': 10} for dotposition in right_hand_numbers: diagramCanvas.create_text(10 + dotposition * 5, dotYposition[dotposition], text='.') print('.') write_cross_hands_dot() mainloop() Can someone see what the mistake is? ThankYou! RE: why is this dictionary giving a Keyerror? - DreamingInsanity - Dec-11-2019 The key of your dictionary is all strings. Your array right_hand_numbers is full of integers.That means you are trying to access the key - of which its type is a string - using an int, so it doesn't find anything and throws an error. What you want is: diagramCanvas.create_text(10 + dotposition * 5, dotYposition[str(dotposition)], text='.')or optionally, make everything in right_hand_numbers a string.
|