Python Forum

Full Version: Pass Dictionary to Method is not possible
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, i have an example project where i try to pass a dictionary as "**kwargs" to a method. Unfortunately this does not work and i dont know why.
Here is my example-Code:
_MyDict = {"age":"25", "name":"Frank"}

def myMethod(**kwargs):
    Name = kwargs.pop('Name', 'InitialName')
    Age = kwargs.pop('Age', 'InitialAge')
    print("Name:" + Name)
    print("Age:" + Age)

myMethod(_MyDict)
By executing this script, i get the following error:

Traceback (most recent call last):
File "main.py", line 17, in <module>
myMethod(_MyDict)
TypeError: myMethod() takes 0 positional arguments but 1 was given


...Program finished with exit code 1
Press ENTER to exit console.


Thanks for Help
spam = {"age":"25", "name":"Frank"}
 
def eggs(**kwargs):
    name = kwargs.get('name', 'Initial Name')
    age = kwargs.get('age', 'Initial Age')
    print("Name:" + name)
    print("Age:" + age)
 
eggs(**spam)
spam = {"name":"Frank"}
eggs(**spam)
Output:
Name:Frank Age:25 Name:Frank Age:Initial Age >>>

It's better to use f-strings or str.format() method
    print(f"Name: {name}")
    print("Age: {}".format(age))
in this case age can be a number and you don't need to cast it as str in order to use in concatenation

spam = {"age":25, "name":"Frank"}
 
def eggs(**kwargs):
    name = kwargs.get('name', 'Initial Name')
    age = kwargs.get('age', 'Initial Age')
    print(f"Name: {name}")
    print(f"Age: {age}".format(age))
 
eggs(**spam)