Maximilian Jirka
Maximilian Jirka

Reputation: 13

How to avoid KeyError in dictionary oneliner

I want to write a oneline encoder but get a KeyError if one of the letters of the message to be encoded is not in the dictionary, how would i avoid that?

def morse_encode(text, code_table):
    return ' '.join(code_table[letter.upper()] for letter in text)

A spacebar (or whitespace) is not defined in that particular code_table dictionary, but instead of an Error i would like to replace a missing key:value pair with one.

Upvotes: 0

Views: 59

Answers (1)

zamir
zamir

Reputation: 2542

You can use .get(key, default) which return key if it is in the dictionary, else default.

E.g.

d = {"a":"1", "b":"2"}
d.get("c") # None
d.get("d", "does not exist") # does not exist

So for your code:

def morse_encode(text, code_table):
    return ' '.join(code_table.get(letter.upper()) for letter in text)

Upvotes: 2

Related Questions