Python Forum
Pass Dictionary to Method is not possible - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Pass Dictionary to Method is not possible (/thread-20562.html)



Pass Dictionary to Method is not possible - Frank123456 - Aug-19-2019

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


RE: Pass Dictionary to Method is not possible - buran - Aug-19-2019

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)