Python Forum
Pass Dictionary to Method is not possible
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pass Dictionary to Method is not possible
#1
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
Reply
#2
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)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I pass a dictionary for the in3_registry value for the Incubed Python API? nilesh 0 419 Jan-11-2021, 11:19 AM
Last Post: nilesh
  Pass by object reference when does it behave like pass by value or reference? mczarnek 2 860 Sep-07-2020, 08:02 AM
Last Post: perfringo
  get method not counting number of strings in dictionary LearningTocode 2 675 Jun-13-2020, 11:17 PM
Last Post: LearningTocode
  Pass by reference vs Pass by value leodavinci1990 1 918 Nov-20-2019, 02:05 AM
Last Post: jefsummers
  How to pass a dictionary as an argument inside setup function of unittest nilaybnrj 1 1,759 May-11-2019, 03:18 AM
Last Post: keames
  need method to look up dictionary key by value league55 3 1,495 Jan-17-2018, 10:58 PM
Last Post: metulburr
  How to pass value from method to function iFunKtion 11 5,867 May-23-2017, 05:06 PM
Last Post: iFunKtion

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020