简体   繁体   English

如何避免字典oneliner中的KeyError

[英]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?我想编写一个单行编码器,但如果要编码的消息的其中一个字母不在字典中,我会得到一个 KeyError,我将如何避免这种情况?

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.在那个特定的 code_table 字典中没有定义空格键(或空格),但是我想用一个替换缺少的键:值对而不是错误。

You can use .get(key, default) which return key if it is in the dictionary, else default.您可以使用.get(key, default)如果它在字典中,则返回键,否则返回默认值。

Eg例如

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM