Python Forum
Error in dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Error in dictionaries
#1
I'm having trouble with an error in my code and I cannot find out why it is happening.

This is the task:
Most non-smartphone mobile phones have keypads like this:

Given a word of input, all in uppercase letters, print the numbers you would need to type on a standard mobile phone keypad to enter that word. Assume that the phone can perfectly predict the word you want, and there are no numbers or punctuation symbols in the word.

For example:


Enter word: GROK
4765

4765 is printed out since GROK is entered by pressing 4, 7, 6, and 5.



This is what I have done so far:
i=0
out=[]
KEYPAD = {
    'A': '2', 'B': '2', 'C': '2', 'D': '3', 'E': '3',
    'F': '3', 'G': '4', 'H': '4', 'I': '4', 'J': '5',
    'K': '5', 'L': '5', 'M': '6', 'N': '6', 'O': '6',
    'P': '7', 'Q': '7', 'R': '7', 'S': '7', 'T': '8',
    'U': '8', 'V': '8', 'W': '9', 'X': '9', 'Y': '9',
    'Z': '9',
}
word=input("Enter word: ")
words=[ch for ch in word]
while len(word)>=i:
  if words[i] in KEYPAD:
    x=KEYPAD[i]
    out.append(x)
    i=i+1
  else:
    i=i+1
print(out)
Output:
Enter word: GROK Traceback (most recent call last): File "program.py", line 15, in <module> x=KEYPAD[i] KeyError: 0
Reply
#2
That's not how you access a dictionary.
This is the proper way:
num = KEYPAD[ch]
Reply
#3
(Jan-04-2018, 12:03 AM)Larz60+ Wrote: That's not how you access a dictionary.
This is the proper way:
num = KEYPAD[ch]


its x = KEYPAD[words[i]]...

also len(word)>i, remove the '=' else list out of index error occured
Reply
#4
You can convert a string to a list using casting, words = list(word), no need to use the list comprehension.

In the while loop, you increment i on both paths through the if statement, so why not have it just once below the if statement? Although, you don't really need a while loop.

Given that you are just looping through words, why not use:

for ch in words: which will give you each letter in turn (you know this already, from using list comprehension earlier).

Why bother with checking if the character is in KEYPAD and then extracting it?
Just use words.get(ch, default_value)

default_value can be left out (in which case, None is returned if there is no match).
I am trying to help you, really, even if it doesn't always seem that way
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020