How can I track key presses in Python and store them in a list?

0
9
Asked By CuriousCoder42 On

I'm working on a Python project where I want to record each keypress in a list. For example, if I press the "A" key, it should be added to the list, and if I press "B", that should go in as well. If I press "A" again, rather than adding it again, the count for "A" should increment, so it shows A = 2, B = 1. I'm hoping I explained that clearly! For convenience, I'd like to eventually store this data in an Excel file or any database.

3 Answers

Answered By NoobProgrammer22 On

Honestly, if you're just starting out, I suggest using two lists. One would store the keys, and the other would keep track of their counts. Every time a key is pressed, you'd check if it’s already in the first list. If it is, you increment its count in the second list; if not, you add it and set the count to 1.

NewbieDev -

That sounds interesting! But how do I capture which key gets pressed?

Answered By CodeMasterPete On

You might want to check out Python's dictionary type. It’s perfect for this since it pairs keys with values. So for you, each key can be a letter, and its value can be how many times you've pressed it. Also, a library called collections.Counter does exactly what you need. It automatically handles counts for you, simplifying the process.

Answered By TechWhiz99 On

You're looking to create a tool that keeps track of how many times each key has been pressed, right? Just a quick question: do you need the keys to be stored in the order they were pressed, or is it fine if they're just counted?

CuriousCoder42 -

Yes, storing them in order would be great, but counts are more important.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.