Vanq8ish
Vanq8ish

Reputation: 23

translating user input in python

I would like to translate items in a list (e.g. [1,2,3,4,5,6,7,8,9]) to items in another list (e.g. the names of those numbers).

Furthermore, I want to be able to do the translation so that when a user inputs '1', "one" is printed, and similarly for '2', etc.

Here's the code I have so far:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 
         'eight', 'nine']
myDict = dict(zip(numbers, names))

Upvotes: 1

Views: 1080

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 184995

Using the input function will allow you to accept input from the user and do the lookup (if I understand what you are asking):

>>> mydict = {'nom':'singe', 'poids':70, 'taille':1.75}
>>> myvar = input()
nom
>>> print(mydict[myvar])
singe

Upvotes: 2

Burhan Khalid
Burhan Khalid

Reputation: 174624

It will not print "nom piods" because you don't have a key for "nom poids".

This will do what you want:

mydict = {'nom':'x', 'poids':'y','foo':'bar'}
print mydict['nom'],mydict['poids']

If you will always be using numbers; and not words - you can do this:

words = ['zero','one','two','three','four','five']
print words[0] # This will print 'zero'
print words[1] # This will print 'one'

print words['1'] # This will not work, you need to use 1 and not '1'

Upvotes: 0

Related Questions