-2

This is my code and i want to put this all in one line:

def GetKey(self, key):

    if key == "externalCode":
        return "ExternalCode"
    elif key == "name":
        return "Name"
    elif key == "description":
        return "Description"
    elif key == "remind-indays":
        return "RemindInDays"
    elif key == "is-delegate-supported":
        return "IsDelegateSupported"
    elif key == "escalation":
        return "Escalation"
kederrac
  • 16,819
  • 6
  • 32
  • 55

4 Answers4

2

Use a dictionary.

key_map = {"externalCode": "ExternalCode", "name": "Name", "description": "Description", "remind-indays": "RemindInDays", "is-delegate-supported": "IsDelegateSupported", "escalation": "Escalation"}

def GetKey(self, key):
    return key_map[key];

This will raise an error if it's given an invalid key. If you really want to return None (as your function does), use the dict.get() method.

def getKey(self, key):
    return key_map.get(key)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    Why use try/except when there's a [convenience method](https://docs.python.org/3/library/stdtypes.html#dict.get) on dicts for this already... – PyPingu Jan 07 '20 at 09:43
  • @PyPingu Good point, I've update the answer to show multiple ways. – Barmar Jan 07 '20 at 09:45
1
you can use a dict instead of your function:

GET_KEY = {
    "externalCode": "ExternalCode",
    "name": "Name",
    "description": "Description",
    "remind-indays": "RemindInDays",
    "is-delegate-supported": "IsDelegateSupported",
    "escalation": "Escalation"}

GET_KEY.get("externalCode")

output:

'ExternalCode'
kederrac
  • 16,819
  • 6
  • 32
  • 55
0

Improved based on suggestions.

word = 'name'
d = {'externalCode': 'ExternalCode', "name": "Name", "description": "Description"}

if word in d:
    word = d[word]
print(word)
Shweta Chandel
  • 887
  • 7
  • 17
0
def stackflow(x):
    key = {
        "externalCode": "ExternalCode",
        "name": "Name",
        "description": "Description",
        "remind-indays": "RemindInDays",
        "is-delegate-supported": "IsDelegateSupported",
        "escalation": "Escalation"
    }
    return key[x]
kederrac
  • 16,819
  • 6
  • 32
  • 55