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

Viewed 168

Here is an example of if-else statement in javascript.

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";
}

A more elegant way is to rewrite the if-else implementation using object.

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";
}

Can python be used to write similar elegant code like javascript object literals?

I am using python 3.8

Javascript code segment is from link below;

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

1 Answers

Python equivalent:

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")

Another useful variation if you don't know the content of the dict and want to ensure a value is always returned:

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

Would get a default value even if a there was a key with a None value in the dict

Related