+ 6
Problem - Dictionaries in Python
My code, given names and phone numbers, assembles a phone book that maps their names to their respective phone numbers. The firs var n, decides number of names to query your phone book for. For each queried, it should print the associated entry from thephone book on a new line(Like: ''joe = 123456''). If the entry is not found, it prints not found. But it prints "Not Found" EVERYTIME! n = int(input()) for i in range(1, n+1): name_i = input() num_i = input() phonebook = { name_i : num_i, } try: for z in range(0, n+1): name_z = input() print(name_z + ' = ' + phonebook[name_z]) except KeyError: print('Not Found')
5 Réponses
+ 5
You have to define phonebook as an empty dictionary, first.
Either:
phonebook = {}
or:
phonebook = dict()
Then, in your first loop you have to ADD to the dictionary instead of assigning it just a recently entered *single* entry.
So either:
phonebook += {name_i: num_i}
or:
phonebook[name_i] = num_i
Also, you might try adding some descriptions to your inputs, so the user knows where he is during the code run.
+ 6
phonebook = {} # added
n = int(input())
for i in range(1, n+1):
name_i = input()
num_i = input()
phonebook[name_i] = num_i # modified
try:
for z in range(0, n+1):
name_z = input()
print(name_z + ' = ' + phonebook[name_z])
except KeyError:
print('Not Found')
+ 4
Thanks ☺ everyone
+ 2
Kuba has already given the right directions!
Here is a little example: https://code.sololearn.com/c7P3sA9Bq3WC
Your phone book is a dictionary with the names of people as the keys and their numbers as the values.
There's more than one way to populate such a dictionary, but reading key-value pairs from a list of tuples probably is one of the easiest.
Once you have filled your phone book, you can either iterate over all keys (=names) and get the corresponding values (=numbers). The more usual way to use a phone book is, of course to look of a name to find the number.
Kuba and visp have already shown that
phonebook[name]
will return the corresponding number. This works great if the name is a key in the dict. If not, this throws a KeyError exception that you need to handle, see the example by visph.
You can avoid this by using the get method of Python dictionaries. This method allows to define a default value which is returned if the name is not a key in the dict.
+ 1
Dictionaries
👇👇👇👇👇👇👇
https://code.sololearn.com/cuWT75qxQa4o/?ref=app