Dictionary - 'str' Object Is Not Callable
I am new to Python and trying to create a user interface with options to insert, delete and update data. THe data will be manipulated in a text file. I wanted to accept option fr
Solution 1:
Strings, such as dict_options[option]
, are not callable, but functions are. Therefore, make the dict_options
values be function objects:
Change
dict_options = {'1' : 'Insert',
'2' : 'Update',
'3' : 'Delete',
'4' : 'Display_number_of_records',
'5' : 'Display_all_records',
'6' : 'Exit'}
to
dict_options = {'1' : Insert,
'2' : Update,
'3' : Delete,
'4' : Display_number_of_records,
'5' : Display_all_records,
'6' : Exit}
Note you'll have to define the functions before defining dict_options
.
Also, to print the name of the function, change value
to value.__name__
:
for key in dict_options.keys():
value = dict_options.get(key)
print(str(key) + ". " + value)
becomes
for key in dict_options.keys():
value = dict_options.get(key)
print(str(key) + ". " + value.__name__)
Solution 2:
EDIT: Looks like unutbu beat me to it.
This line:
dict_options[option]()
Evaluates to something like this:
'Some String'()
You cannot call a string like this (try it!). You'll have to edit your dictionary so the values inside are functions (or some other kind of callable object), not strings.
EDIT:
Assuming the string values in your dictionary are the names of callable objects (e.g. functions), you COULD make it work the way you have it using exec
:
exec(dict_options[option] + '()')
Post a Comment for "Dictionary - 'str' Object Is Not Callable"