I want to use a dictionary to call functions with arguments, ie this simple program. I'm a very novice coder in python. what am I doing wrong? output:
what name? : s
what name? : f
f
s
want to write or read? w/r:
w
want singers or band members? s/b:
s
1
code:
def addToFile(filename, lineString):
file = open(filename,"a")
file.write(lineString "\n")
file.close()
return 1
def readFile(filename):
file = open(filename)
for line in file:
print(line)
file.close()
return 2
whatToDo = {
"ws": addToFile("band.txt",input("what name? : ")),
"wb": addToFile("singers.txt",input("what name? : ")),
"rs": readFile("singers.txt"),
"rb": readFile("band.txt")
}
def promptWrite():
print("want to write or read? w/r: ")
choice = str(input())
print("want singers or band members? s/b: ")
choice = str(input())
val = whatToDo[choice]
print(val)
promptWrite()
I didn't know If I needed to have a value or something, so I put the returns in the functions and had val. That isn't nessisary, I just drafted this up as an example program.
I know that you can have a dictionary with the names of the functions and call
dictionaryName[whateverthing]()
to run the function, but I don't know how to have the arguments vary in that
CodePudding user response:
You're calling the functions when you create the dictionary, not when you access the dictionary. Use lambda
to create anonymous functions, then add ()
when you fetch from the dictionary to call it.
def addToFile(filename, lineString):
file = open(filename,"a")
file.write(lineString "\n")
file.close()
return 1
def readFile(filename):
file = open(filename)
for line in file:
print(line)
file.close()
return 2
whatToDo = {
"ws": lambda: addToFile("band.txt",input("what name? : ")),
"wb": lambda: addToFile("singers.txt",input("what name? : ")),
"rs": lambda: readFile("singers.txt"),
"rb": lambda: readFile("band.txt")
}
def promptWrite():
print("want to write or read? w/r: ")
choice = input()
print("want singers or band members? s/b: ")
choice = input()
val = whatToDo[choice]()
print(val)
promptWrite()
CodePudding user response:
You can't set functions with parameters to be executed in a dictionary, but you can store functions to call them after, with the corresponding dict key and parenthesis. Example:
my_dict['write_output'] = print
my_dict['write_output']('hello from my key')
IMHO, storing your functions in dict keys is a design incosistency. Dicts are mutable objects, then someone could overwrite your keys without any restriction and mess up your code everywhere. Not a good idea at all.