Search code examples
pythonpython-2.7dictionaryargskeyword-argument

Function which return dictionary of arguments in python


Function func(*args, **kwargs) should return dictionary, and all elements of that dictionary should be numeric or string variables. If argument of function is dictionary, then function should return dictionary with all elements of argument dictionary, and other arguments. For example:

arg1 = { 'x': 'X', 'y': 'Y' }  
arg2 = 2
arg3 = { 'p': arg1, 'pi': 3.14 }
func(arg2, arg3, arg4=4)

should return this:

{ 'x': 'X', 'y': 'Y', 'arg2': 2, 'pi': 3.14, 'arg4': 4 }

How to do that? Recursion is not desirable.


Solution

  • You could do something like this - but that solution needs argument numbers ascending (arg1, arg2, ..., argN).

    def func(*args, **kwargs):
        res = {}
        for i, a in enumerate(args):
            if isinstance(a, dict):
                res.update(a)
            else:
                res['arg%s' % (i+1)] = a
        res.update(kwargs)
        return res
    
    
    arg1 = { 'x': 'X', 'y': 'Y' }  
    arg2 = 2
    arg3 = { 'p': arg1, 'pi': 3.14 }
    
    myDict = func(arg1, arg2, arg3, arg4=4)
    print(myDict)
    

    returns:

    {'x': 'X', 'y': 'Y', 'arg2': 2, 'p': {'x': 'X', 'y': 'Y'}, 'pi': 3.14, 'arg4': 4}