Reputation: 39
I have to create a dictionary using a list filled with tuples. Every tuple should be a pair, e.g. (word, description_of_said_word). So far I have this:
banana = ("banana", "a yellow fruit")
orange = ("orange", "a orange fruit")
apple = ("apple", "a green fruit")
my_list = [banana, orange, apple]
def lookup():
word = raw_input("Word to lookup: ")
print ("\n")
n = my_list.index(word)
x = my_list[n][0]
y = my_list[n][1]
if word == x:
print x, ":", y, "\n"
else:
print("That word does not exist in the dictionary")
lookup()
When I write in banana I get an error saying, "ValueError: 'banana' is not in the list". What am I doing wrong?
Upvotes: 0
Views: 23991
Reputation: 374
One way to do this is to loop through the list of tuples and compare the input word to the first item in each tuple. If it matches, then print and return. If it makes it through the whole list without finding a match, let the user know that word doesn't exist.
banana = ("banana", "a yellow fruit")
orange = ("orange", "a orange fruit")
apple = ("apple", "a green fruit")
my_list = [banana, orange, apple]
def lookup():
word = raw_input("Word to lookup: ")
print ("\n")
for fruit in my_list:
if fruit[0] == word:
print fruit[0], ":", fruit[1], "\n"
return
print("That word does not exist in the dictionary")
lookup()
Upvotes: 1
Reputation: 36043
"banana"
is not in my_list
. ("banana","a yellow fruit")
is. These are different objects.
If you instead use my_dict = dict([banana,orange,apple])
you will get an actual dictionary in which "banana"
is a key and my_dict["banana"]
will give you "a yellow fruit"
.
Read more here: https://docs.python.org/2/library/stdtypes.html#mapping-types-dict
Upvotes: 1