Search code examples
pythonpython-3.xone-liner

How to pass extra variable to function if conditions are met


Say I have the following python code:

hp = 0
if 'header' is in paramdict.keys():
    hp = paramdict['header']
mydf = [pd.read_excel(xlsx, sheet, header = hp) for sheet in xlsx.sheet_names]

I only want to pass header if it's in paramdict. (default value is 0)

Is there a better way to do this, or one that's easier on the eyes / takes up less space? I've tried fstrings and eval but haven't been able to get them to work.


Solution

  • dict has a .get method that allows you to pass a default value that gets returned if the key is not present in the dict

    hp = paramdict.get('header', 0)
    mydf = [pd.read_excel(xlsx, sheet, header=hp) for sheet in xlsx.sheet_names]
    

    Here's an example,

    >>> d = {'one': 1, 'two': 2}
    >>> d
    {'one': 1, 'two': 2}
    >>> d.get('one', 'Nope, not here')
    1
    >>> d.get('three', 'Nope, not here')
    'Nope, not here'