Python 我应该如何基于字典键的存在有条件地赋值?

Python 我应该如何基于字典键的存在有条件地赋值?,python,Python,我有一些Perl代码如下: my $match = $matches{$key} ? "$matches{$key} was a match!" : "There was no match." 如何最好地用Python重写?我试图避免出现按键错误。这是一个错误 message = "%s was a match"%(matches[key],) if key in matches else "There was no match." Plzse

我有一些Perl代码如下:

my $match = $matches{$key}
            ? "$matches{$key} was a match!"
            : "There was no match."
如何最好地用Python重写?我试图避免出现按键错误。

这是一个错误

message = "%s was a match"%(matches[key],) if key in matches else "There was no match."

Plzsendtehcodez。你不能综合这两个答案?为什么,在匹配[键]中是必要的?我可以这么说吗?message=“%s是匹配项”%matches[key]if key in matches else“没有匹配项”不需要逗号。然而,始终使用tuple作为%string格式的正确参数是一种很好的风格。@Benjamin Peterson:只是出于好奇,为什么?format%tuple是标准格式;(x,)是一个单元组。(x,y)是两元组(“双”),(z,y,x)是三元组(“三元组”)。如果(且仅当)值本身不是序列,Python可以容忍格式%value。字符串是序列。所以通常需要格式%(字符串,)。