2

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

user3848207
  • 3,737
  • 17
  • 59
  • 104
  • Yes you can do the same thing with python dictionaries – Shubham Periwal Apr 22 '21 at 00:59
  • May I ask why the 2 negative votes? What's wrong with the question? – user3848207 Apr 22 '21 at 01:03
  • 1
    Not a downvoter, but this is basically asking how to do almost exactly the same thing in Python as in JS. Both of which are poorly emulating `switch` statements, so the answers to [Replacements for switch statement in Python?](https://stackoverflow.com/q/60208/364696) should cover you. – ShadowRanger Apr 22 '21 at 01:18

1 Answers1

2

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

pcauthorn
  • 370
  • 1
  • 8
  • 1
    Note that the CPython reference interpreter lacks any optimizations to avoid rebuilding the `dict` on every call, so if you're looking for performance gains, you want to put the definition of `rhymes` *outside* the function, not inside. That way, it only gets built once, and reused on every call without rebuilding it. – ShadowRanger Apr 22 '21 at 01:16