Home > Back-end >  How to convert a number into words based on a dictionary?
How to convert a number into words based on a dictionary?

Time:12-05

First, the user inputs a number. Then I want to print a word for each digit in the number. Which word is determined by a dictionary. When a digit is not in the dictionary, then I want the program to print "!".

Here is an example of how the code should work:

Enter numbers : 12345
Result: one two three ! !

Because 4 and 5 are not in Exist our dictionary, the program has to print "!".

DictN= {
    '1':'one',
    '2':'two',
    '3':'three'
}
InpN = input('Enter Ur Number: ')

for i,j in DictN.items():
    for numb in InpN:
        if numb in i:
            print(j)
        else:
            print('!')

MY WRONG OUTPUT

one
!
!
!
!
two
!
!
!
!
three
!

Process finished with exit code 0

CodePudding user response:

# Consider the input as an int
indata = input('Enter Ur Number: ')

for x in indata: print(DictN.get(x,'!'))

CodePudding user response:

The solution to your problem can be programmed pretty much exactly how it's written in english, like this:

DictN = {
    '1':'one',
    '2':'two',
    '3':'three'
}
InpN = input('Enter Ur Number: ')

for i in InpN:
    if i in DictN:
        print(DictN[i])
    else:
        print("!")

gerrel93 explained how to retrieve data from a dictionary, and for many methods regarding iterables (objects such as strings and lists), dictionaries are treated as a list of their keys. The in keyword is one example of this.

CodePudding user response:

a dict works like this:

# the alphabetical letters are the keys, and the numbers are the values which belong to the keys
a = {'a': 1, 'b': 2}

# if you want to have value from a it would be 
print(a.get('a'))
# or
print(a['a'])

# which is in your example:
DictN= {
    '1':'one',
    '2':'two',
    '3':'three'
}
InpN = input('Enter Ur Number: ')
print(DictN[InpN])

in your example you could do something like this

DictN= {
    '1':'one',
    '2':'two',
    '3':'three'
}
InpN = input('Enter Ur Number: ')
for i in InpN:
  print(InpN[i], '!')

by the way you would not use these variable names in Python. This source is good for best practices: https://peps.python.org/pep-0008/ https://python-reference.readthedocs.io/en/latest/docs/dict/get.html

CodePudding user response:

The problem with your code is that you loop over the dictionary, and then check whether a certain value is in the input. You should do this in the reverse way: Loop over the input and then check whether aech digit is in the dictionary:

DictN= {
    '1':'one',
    '2':'two',
    '3':'three'
}
InpN = input('Enter Ur Number: ')

for digit in InpN:
    if digit in DictN:
        print(DictN[digit], end=" ")
    else:
        print("!", end=" ")
print("")

The output is the following:

Enter Ur Number: 12345
one two three ! ! 

So, first we define the dictionary DicN and receive the input in InpN exactly as you did. Then we loop over the string we received as input. We do this because we want to print a single character for each digit. In the loop, we check for each digit whether it is in the dictionary. If it is, then we retreive the correct word from the dictionary. If it isn't, then we print !.

Do also note that I used end=" " in the prints. This is because otherwise every word or ! would be printed on a new line. The end argument of the print function determines what value is added after the printed string. By default this is "\n", a newline. That's why I changed it to a space. But this does also mean that we have to place print() after the code, because otherwise the following print call would print its text on the same line.

CodePudding user response:

Since the other answers already show you how to use a dictionary, thought I'd demonstrate an alternative way of solving your problem. Would have written this as a comment, but I don't have enough reputation :)

The hope is that this helps you learn about iterators and some neat builtins

inp = input("Enter Ur Number: ")

words = ["one", "two", "three"]
dict_n = dict(zip(range(1, len(words)   1), words))
print(" ".join([dict_n.get(int(n), "!") for n in inp]))

Breaking it down

>>> range(1, len(words)) # iterator
range(1, 3)

>>> dict(zip([1,2,3], [4,5,6])) # eg: zip elements of two iterators
{1: 4, 2: 5, 3: 6}

>>> dict(zip(range(1, len(words)), words))
{1: 'one', 2: 'two'}

>>> [n for n in range(3)] # list comprehension
[0, 1, 2]

>>> " ".join(["1", "2", "3"])
'1 2 3'

Hope the above block helps break it down :)

CodePudding user response:

Alternative using map:

DictN={'1':'one','2':'two','3':'three'}
print(*map(lambda i:DictN.get(i,'!'),input('Enter Ur Number: ')),sep=' ')

# Enter Ur Number: 12345
# one two three ! !
  • Related