(Python(所以我设置了一个嵌套字典,类似于:
{spanish word: {english word: .5, english word 2: .3, ...}}
其中键是西班牙语单词,值是嵌套字典,其键是英语单词及其概率。我想得到西班牙语单词,使其具有最大值。我试过(当前西班牙语单词(
maxenglish = max(d[word], key = d[word].get)
但这会返回英语单词。我对lambda函数不太熟悉,但我看到了它可以被使用吗?谢谢你的帮助!
编辑:切换英语和西班牙语
示例:
nesteddict = {"hola": {"hello":.5,"goodbye":.1}, "ciao": {"hello":.1,"goodbye":.5}
word = "hola"
argmax = max(nesteddict[word], key = nesteddict[word].get)
返回";你好;但我希望它能回来";hola";。
这是您需要的吗?它需要字典和需要最合适翻译的单词。因此,它通过获得最大分数来返回最适合的单词。
def get_best_word(nesteddict, wd):
max_score = 0
key_with_max_score = ""
for k in nesteddict:
for sk in nesteddict[k]:
current_score = nesteddict[k][sk]
if sk == wd and current_score > max_score:
key_with_max_score = k
max_score = current_score
print(key_with_max_score)
或者,您可以使用max函数来完成此操作,方法是将lambda函数作为参数传递给键max(nesteddict.keys(), key=lambda k: nesteddict[k]["hello"])
但是,如果在所有嵌套字典中都没有hello
密钥,则后者将抛出错误