How to store Python function in Value of dictionary (dict) and call function according to Key

1. Declare a method (function)

Python3


def sample_func_1(text : str) -> str:
    add_text = "Added string"
    return (text + add_text)


def sample_func_2(text : str) -> str:
    add_text2 = "Added string"
    return (text + add_text2)

2. Write the function in * Value * of the dictionary type (* dict *) object without parentheses.

Python3


func_dict = {
	'label_1' : sample_func_1,
	'label_2' : sample_func_2
	}

3. Call and execute the function with the dictionary type object * Key * label name

The value value of the dictionary (* dict ) is the function (method) object itself. Therefore, in order to execute a function (method), it is necessary to add parentheses ("()") to receive the argument to the value value of the dictionary ( func_dict *).

The result of calling the function (method) "itself" stored as the value value of the dictionary (* dict *) without parentheses ("()") is as follows.

Python3


func_dict['label_1']
<function sample_func_1 at 0x100bafb80>

To execute a function (method) called from a dictionary with the above code, you need to put parentheses ("()") to receive the argument.

Python3


func_dict['label_1']()

__ If * funct_dict * is a method that receives one or more arguments, an error will occur if you call the function without giving any arguments. __

The defined method (function) was a function that takes an object of type * str * as an argument. Pass an appropriate character string as an argument and execute the method (function) stored in * func_dict *.

Python3


func_dict['label_1']("vxw")
#Execution result
'vxw Added string'

(Reference)

Python3


func_dict
#Execution result
{'label_1': <function sample_func_1 at 0x100bafaf0>, 'label_2': <function get_text_from_ppt at 0x100bafa60>}

func_dict['label_1']
<function sample_func_1 at 0x100bafb80>

type(func_dict['label_1'])
#Execution result
<class 'function'>

type(func_dict['label_1']())
#Execution result
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sample_func_1() missing 1 required positional argument: 'text'

type(func_dict['label_1']("giho"))
#Execution result
<class 'str'>

func_dict['label_1']("giho")
#Execution result
'giho added string'

returned_value = func_dict['label_1']("giho")
returned_value
#Execution result
'giho added string'

(Referenced Web page)

  1. @ satoichi's Qiita article "[Python] Execute functions collectively using a dictionary"
  2. "Dictionary of keyword arguments using [Python] **"

(Usage)

By using the method introduced this time, it is possible to call the function (method) corresponding to the * Key * according to the value of * Key * defined in the dictionary type object.

This is useful when you need logic to switch the appropriate function (method) to be called depending on the conditions in the flow of processing data.

As a basic example, you can think of a situation where a function (method) that performs the required processing for the file is dynamically selected, called, and executed according to the contents of the extension of the read file.

The code to cut out only the text character string and acquire the data from the PDF file, Word file, and Excel file is introduced on the following Web page.

  1. deecode blog "[Python] Library sample code for extracting text from Word / Excel / PowerPoint / PDF"
  2. @ butada's Qiita article "Text mining from pdf / docx files"

Python3


def get_text_from_txt(filename : str) -> str:
Read the text file stored in the path received as filename and read the text*str*Processing to get as an object and output as a return value

    return text

def get_text_from_pdf(filename : str) -> str:
Read the PDF file stored in the path received as filename, extract the text string, and one*str*Processing to concatenate to an object and output as a return value
    return text

def get_text_from_word(filename : str) -> str:
Read the Word file stored in the path received as filename, extract the text string, and one*str*Processing to concatenate to an object and output as a return value
    return text

def get_text_from_excel(filename : str) -> str:
Read the Excel file stored in the path received as filename, extract the text string, and one*str*Processing to concatenate to an object and output as a return value
    return text

func_dict = {
	'txt' : get_text_from_txt,
	'pdf' : get_text_from_pdf,
    'word' : get_text_from_word,
    'excel' : get_text_from_excel
         }

(Remarks)

When storing a function (method) in * Value * of the dictionary, if you put parentheses in the function, the following error will occur. If you are trying to execute a function, it will be interpreted.

PZython3


func_dict = {
	     'label_1' : sample_func_1(),
	     'label_2' : sample_func_2()
		 }
#Execution result
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: sample_func_1() missing 1 required positional argument: 'text'
 

Defining a dictionary In the code above, you can define a dictionary (no error) by giving a specific argument in the parentheses of * sample_func_1 () *.

However, the function stored in * Value * of the dictionary becomes a function that can receive only the arguments received when defining the dictionary.

__ (Dictionary definition) __

Python3


func_dict = {
    'label_1' : sample_func_1("abc"),
    'label_2' : sample_func_2("def")
}

__ (Calling a function in the dictionary) __

Python3


func_dict['label_1']
#Execution result
'abc added string'

Python3


func_dict['label_1']()
#Execution result
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

Python3


func_dict['label_1']("abc")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

Python3


unc_dict['label_1']('abc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable


(Remark 2)

__ Store a text string in * Val * of the dictionary and use * eval * and * exec * to call the function. __

__ However, it is not elegant because the number of strokes on the keyboard increases. __

Python3


func_dict = {
    'label_1' : "sample_func_1({arg})",
    'label_2' : "sample_func_2({arg})"
    }

Python3


func_dict
#Execution result
{'label_1': 'sample_func_1({arg})', 'label_2': 'sample_func_2({arg})'}
 
func_dict['label_1']
#Execution result
'sample_func_1({arg})'

expression = func_dict['label_1'].format(arg="'123'")
expression
#Execution result
"sample_func_1('123')"


eval(expression)
#Execution result
'123 Added string'

result = eval(expression)
result
#Execution result
'123 Added string'

add_text = "result2="
text = add_text + expression
text
#Execution result
"result2=sample_func_1('123')"

exec(text)
result2
#Execution result
'123 Added string'

Recommended Posts

How to store Python function in Value of dictionary (dict) and call function according to Key
[Python] How to sort dict in list and instance in list
[python] How to check if the Key exists in the dictionary
How to achieve access by attribute and retention of insertion order in Python dict
[python] Summary of how to retrieve lists and dictionary elements
Comparison of how to use higher-order functions in Python 2 and 3
Get the value of a specific key up to the specified index in the dictionary list in Python
How to check if the contents of the dictionary are the same in Python by hash value
How to check the memory size of a dictionary in Python
I want to use both key and value of Python iterator
How to use is and == in Python
How to get a value from a parameter store in lambda (using python)
How to generate permutations in Python and C ++
Summary of how to import files in Python 3
Summary of how to use MNIST in Python
How to get dictionary type elements of Python 2.7
[Python] How to use hash function and tuple.
How to plot autocorrelation and partial autocorrelation in python
How to retrieve the nth largest value in Python
How to get the number of digits in Python
How to define Decorator and Decomaker in one function
How to write a list / dictionary type of Python3
[Python] How to call a c function from python (ctypes)
How to call a function
How to develop in Python
How to swap elements in an array in Python, and how to reverse an array.
How to use the __call__ method in a Python class
Applied practice of try/except and dictionary editing and retrieval in Python
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
[Python] Summary of how to use split and join functions
How to develop in a virtual environment of Python [Memo]
How to sample from any probability density function in Python
How to get the last (last) value in a list in Python
How to get all the keys and values in the dictionary
How to get a list of built-in exceptions in python
How to execute external shell scripts and commands in python
How to log in to AtCoder with Python and submit automatically
Overview of Python virtual environment and how to create it
How to create an instance of a particular class from dict using __new__ () in python
[Python] How to delete rows and columns in a table (list of drop method options)
[Super easy! ] How to display the contents of dictionaries and lists including Japanese in Python
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
How to auto-update App Store description in Google Sheets and Fastlane
[Python] How to do PCA in Python
How to determine the existence of a selenium element in Python
How to install OpenCV on Cloud9 and run it in Python
How to know the internal structure of an object in Python
How to collect images in Python
How to use SQLite in Python
How to check the memory size of a variable in Python
[Introduction to Udemy Python3 + Application] 49. Function citation and return value declaration
[Python] How to get the first and last days of the month
How to use functions in separate files Perl and Python versions
[Python] Execution time when a function is entered in a dictionary value
How to judge that the cross key is input in Python3
Difference in how to write if statement between ruby ​​and python
How to use Mysql in python
[Python] How to get a value with a key other than value with Enum
[ROS2] How to describe remap and parameter in python format launch
How to wrap C in Python
How to use ChemSpider in Python