Use dictionary to resolve argument in Python

I am new to python and learning Dictionary. I am ended up writing the following program in which I am trying to use dictionary to resolve the argument.

Program :

def fun1(self)
    options = {'abc': '123', 'edf': '456'}
    args = {'op': options[self.arg]}

Now, let's assume that I am passing either 'abc' or 'edf' as argument which I am successfully storing in arg.

Now, what I want to do here is that I want to fetch value according to the key that passed as argument and want to store that value in op

So, is there any problem here in my approach? Are the dictionary tend to use this way? How to achieve this with or without Dictionary?

1 answer

  • answered 2018-04-14 15:28 sanzoghenzo

    I use mapping dictionaries like this extensively, they are a good way to avoid mutliple if/elif/else statements.

    Just be sure to catch missing keys:

    args = {'op': options.get(self.arg, None)}

    Or if you don't want to store anything in args:

    args = {'op': options[self.arg]} if self.arg in options else None