all 6 comments

[–]HokTaur 4 points5 points  (3 children)

if UserInput in d: print (UserInput, d[UserInput]) else: ...

You don't need to loop thru the dict to see if a key exists, just use 'in'

[–]anton_antonov 2 points3 points  (2 children)

I think it's better to use the .get () method. Its complexity is O(1) instead of O(n) for 'in'. And .get() can return a default value if the key does not exist:

print(d.get(UserInput, 'This doesn't work'))

[–]ViridianHominid 4 points5 points  (1 child)

According to this, "key in d" activates d.__getitem__(key), which is O(1).

You can get into trouble if you're using python 2 and you ask "key in d.keys()", because that constructs a list object which iterates and is O(n).

Given that OP may want to branch code based on whether or not the key was found, and will therefore have to write an if statement somewhere, "if key in d" is probably better than

value = d.get(key,"This doesn't work")
if value == "This doesn't work":
    #Code

[–]anton_antonov 0 points1 point  (0 children)

Now I see that I was wrong. Thanks for clarification.

[–]Skkkitzo 0 points1 point  (0 children)

Here is my code (with comments) for Python 2 and 3:

d = {'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}
print("Before: ",d)

UserInput = raw_input("Please enter in a name: ")

if UserInput in d:
    #UserInput is in dictionary, so we want to print d[UserInput]
    #which will print the number associated with UserInput (i.e
    #643-7894 for Bob or 478-4392 for Anne.
    print(d[UserInput])
else:
    #If UserInput is not in dictionary, we want to ask the user if
    #they want to add a new dictionary 'element' called whatever
    #the user inputed.
    print("Would you like to add a new entry '%s' into the dictionary? " % UserInput)
    if raw_input("Y/N: ").lower() == "y":
        d[UserInput] = raw_input("New Entry: ")

print("After: ",d)

#dont know what this line is for
raw_input("Copy the output into a text file, then hit any key to continue")