Python Add to dictionary loop


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

Answers:


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