使用 python 重写 if-else 语句,如 javascript 对象字面量

Use python to rewrite if-else statements like javascript object literals

这里是 javascript.

中 if-else 语句的例子
function getTranslation(rhyme) {
  if (rhyme.toLowerCase() === "apples and pears") {
    return "Stairs";
  } else if (rhyme.toLowerCase() === "hampstead heath") {
    return "Teeth";
  } else if (rhyme.toLowerCase() === "loaf of bread") {
    return "Head";
  } else if (rhyme.toLowerCase() === "pork pies") {
    return "Lies";
  } else if (rhyme.toLowerCase() === "whistle and flute") {
    return "Suit";
  }

  return "Rhyme not found";
}

更优雅的方法是使用对象重写 if-else 实现。

function getTranslationMap(rhyme) {
  const rhymes = {
    "apples and pears": "Stairs",
    "hampstead heath": "Teeth",
    "loaf of bread": "Head",
    "pork pies": "Lies",
    "whistle and flute": "Suit",
  };
  
  return rhymes[rhyme.toLowerCase()] ?? "Rhyme not found";
}

python 可以用来编写类似于 javascript 对象字面量的优雅代码吗?

我正在使用 python 3.8

Javascript代码段来自下面link;

https://betterprogramming.pub/dont-use-if-else-and-switch-in-javascript-use-object-literals-c54578566ba0

Python相当于:

def get_translation_map(rhyme): 
    rhymes = {
       "apples and pears": "Stairs",
       "hampstead heath": "Teeth",
       "loaf of bread": "Head",
       "pork pies": "Lies",
       "whistle and flute": "Suit"
    }
    return rhymes.get(rhyme.lower(), "Rhyme not found")

如果您不知道 dict 的内容并希望确保始终返回一个值,另一个有用的变体:

  v = adict.get('whatever') or 'default'

即使在 dict

中有一个具有 None 值的键,也会得到一个默认值