Exactly Why

This is exactly why I started this site.

I’m currently working on this first project of mine, and I find myself stuck with dictionaries. I know what I want to do–check to see if a key is in the dictionary–but I don’t know how to do it. I know how to call a key and get its value, but I can’t work out how to first check to see if the key is in the dictionary in the first place, and then if it is, get the value relating to it.

So far, I have this:

#260513_simple_address_book

the_book = {'Dan': 23, 'Peter': 24}


def check_name_in_book():
    user_name = get_user_name()
    if user_name in dict.keys:
        print('Your name is in the book, ', user_name, ' age: ', the_book[user_name])
    else:
        print('Your name is not in the book, ', user_name)
    

def get_user_name():
    print('Please enter your name: ')
    user_name = input('')
    return user_name


check_name_in_book()

All of it is working as I would expect, except line 8. Now line 8 as it is now is only the current iteration of very many different versions of that line, such as:

if user_name == the_book[user_name]

For a long time I thought that that made perfect sense. Of course I realise now that it doesn’t make any sense at all, and that is partly the reason I started this blog. Every time I used a forum for AppleScript help while I was a newbie, I was always given the right information, but invariably no explanatory information. The same thing is happening now. I could just copy and paste the bits of code I find in forums into my projects, but as they have no explanations next to them, I’ll never learn anything, and that is what I want to do. I want to learn Python, not just copy and paste bits that someone else made into my projects.

So, the reason that the ‘==’ version doesn’t work is because of what I’m comparing user_name to.

In this case, the_book[user_name] return the value ’23’ because that is the value that is assigned to the key ‘Dan’. What I want to do is find out if the key ‘Dan’ is in the dictionary in the first place. Only then do I want to know what the value of ‘Dan’ is.

When I find the right answer to this question, I’ll post it and explain it.

Author: Dan

Share This Post On