This function is supposed to add a name and number to the dictionary 'phoneBook' when I run the loop, but for some reason I can't get it to work. Any ideas on why not? Thanks a lot!
phoneBook = dict()
def addNumber(name, number):
for i in phoneBook:
if i == name:
print 'error'
else:
phoneBook[name] = number
You don't really need the loop at all, you can just use the in
keyword to check the name against the existing keys in the dictionary.
phoneBook = dict()
def addNumber(name, number):
if name in phoneBook:
print 'error'
else:
phoneBook[name] = number
why bother
people = ((data["name"],data["number"]) for data in json.loads(some_list)[::-1])
phoneBook = dict(people)
this will run in reverse order through the list so the first occurrence of the name will be the one stored in the dictionary
it takes longer to check than to just insert it ... even if it ends up over written
to answer your question however
your original code did not work because your else was inside the forloop essentially adding the entry if any name in the book did not match the name being inserted
you can fix it easily enough, by exiting the function when a match is found... and not adding the name to the dictionary until you have checked all names
phoneBook = dict()
def addNumber(name, number):
for i in phoneBook:
if i == name:
print 'error'
return
phoneBook[name] = number
addNumber("james",56)
addNumber("Tommy",26)
addNumber("james",77)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With