Blake Rowden
Blake Rowden

Reputation: 145

Returning string in place of None without if statement

Is it possible to achieve the same outcome as the code below without making a temp variable and not using a if statement? I have tried multiple things but I am quite new to python.

 def get_value(dictionary, key):
    temp = dictionary.get(key)
    if temp = None:
        return "Sorry this item doesn't exist"
    else:
        return temp

i.e. of what I am trying to achieve

 def get_value(dictionary, key):
     return dictionary.get(key) else return "Sorry this item doesn't exist"

Upvotes: 0

Views: 57

Answers (2)

chepner
chepner

Reputation: 531325

Returning a string instead of None is something of an anti-pattern, since there's no way to distinguish between "Sorry this item doesn't exist" as an error message or as the actual value associated with the given key. Raise an exception instead.

def get_value(dictionary, key):
    try:
        return dictionary[key]
    except KeyError:
        raise Exception("Sorry, this item doesn't exist")

You can define your own custom exception in place of Exception. Also consider whether your exception really adds anything of value over the KeyError already raised by dict.__getitem__.

Upvotes: 1

brandonwang
brandonwang

Reputation: 1653

You can specify a default value when calling get() on a dictionary. Try this:

def get_value(dictionary, key):
    default = "Sorry this item doesn't exist"
    return dictionary.get(key, default)

Upvotes: 6

Related Questions