Search code examples
pythonpython-2.7user-inputkeyword-argument

how to call a function contains kwargs with input function data?


I have a function :

def myFunc(**kwargs):
    for username, password in kwargs.iteritems():
        print "%s = %s" % (username, password)

I want to receive username and password using input like this :

username = input("Enter username : ")
password = input("Enter password : ")

Then pass username and password to myFunc :

myFunc(username = password)

I know that it's not gonna working, but what is the solution to handle this job ?

Note : both username and password may be different things in every iteration.


Solution

  • You need to use the ** syntax to expand a dict into its constituent key/value pairs. For example:

    myFunc(**{username: password})
    

    or

    d = {}
    d[username] = password
    myFunc(**d)