Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 456
bugsyb Avatar asked Oct 08 '14 18:10

bugsyb


2 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
like image 116
Cory Kramer Avatar answered Sep 22 '22 06:09

Cory Kramer


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)
like image 44
Joran Beasley Avatar answered Sep 18 '22 06:09

Joran Beasley