Search code examples
pythonpython-3.4argument-passing

Combine single and multi argument variables in a function call for Python


I wrote the following function to return a subset of a dictionary but want to insist on having at least one key provided in the input arguments.

def getProperty(self,x, *key):
    key = [k for k in key]
    key.insert(0,x)
    return {k:self.__properties[k] for k in key if k in self.__properties}

The code works.

I know the insert is not really necessary since dictionary elements aren't ordered. What I really wish I could do is to get rid of the first for-loop that creates a list by extracting elements from the multi-argument tuple.

Something like

key = [x] + [key]

but it does not work.


Solution

  • This should do what you need:

    def getProperty(self,x, *key):
        key = (x,)+key
        return {k:self.__properties[k] for k in key if k in self.__properties}