Using .get() method within if statement


I’m going through the solutions to the Abruptly Goblins project in Learn Python 3. I’m confused by this code below.

kimberly = {
    'name': "Kimberly Warner",
    'availability': ["Monday", "Tuesday", "Friday"]

For context, kimberly is a dictionary within a list called gamers, but that shouldn’t matter for the question here.

def add_gamer(gamer, gamers_list):
    if gamer.get("name") and gamer.get("availability"):
        print("Gamer missing critical information")

I’m confused because I thought the .get() method returns the value of the specified key in the argument. Since if statements only run when the condition(s) in the statement is True, how does this make sense? Wouldn’t it be like writing if 'Kimberly Warner' and '["Monday", "Tuesday", "Friday"]': ? This makes no sense and would produce an error if I’m not mistaken…?

Link to project:

That’s basically just checking if there exists the key "name" and "availability" in the dictionary. Because .get() returns None if the key you’re trying to access doesn’t exist, you can use it to check whether a key exists in a certain dictionary or not:

some_dict = {"hello": "world"}
print(some_dict.get("hello") #output: world
print(some_dict.get("hi") #output: None

That works because every object’s value can be evaluated as either “truthy” or “falsy”. A truthy value is a value that, if cast to a bool, would return true (and vice-versa with falsy values). Because None is a falsy value, if either key does not exist in the dictionary, the if block won’t run:

some_dict = {"hello": "world"}
#output: False, because None is a falsy value

I hope this helps!

Bear in mind that get() is falsy only when the attribute does not exist. If the attribute exists, its value can still be falsy. This potential for discrepancy of interpretation should be made transparent.

1 Like

I find this answer to be very “truthy”.

Thanks for the quick reply!

1 Like

True enough; sorry! I meant that everything in Python can be evaluated as truthy or falsy, for example: all strings are either truthy or falsy, etc.

1 Like