More ‘Pythonic’ way to write asymmetric if-else statement

You can use dict.get() here:

if name_dict.get(name):
    info = name_dict['name'] 
else:
    info = input("Input your info: ")

name_dict.get(name) will only be true if name exists as a key in name_dict, and the value associated with the key is not an empty value ('' is false in a boolean context, if name is missing None is returned, which is also a false value).

These two lines can be combined with or, eliminating the if statement altogether:

info = name_dict.get(name) or input("Input your info: ")

That’s because or short-circuits. If name_dict.get(name) produces a non-empty value, the input() function will not be called.

Leave a Comment