In this article, we will see how we can specify the argument type for a list of Dictionary for Python.
As we know, Python is a dynamically typed language so the data type of a variable can change anytime. If a variable containing an integer may hold a string in the future, which can lead to Runtime Errors, Therefore knowing the data type of the arguments becomes important for a function. Here we will use a typing python module which help us to resolve this problem.
So, In general, we can write a function in Python as:
Python3
def add(a, b): return a + b |
But here, we don’t know if the function ‘add’ accepts int or float values. PEP 3107 Function Annotations now enable us to write our code as:
Python3
def add(a: int , b: int ) - > int : return a + b |
Now we can easily tell by reading the code what is the expected data type of the parameters and output.
So, now for Specifying Argument Type for List of Dictionary for a python function. It will be as simple as
Example 1:
Here we can see:
- The datatype for arguments.
- The type of output is a list that contains a Dictionary with values – a string and integer.
Python3
# typing is a standard library from typing import List , Dict def GetData(name: str , age: int ) - > List [ Dict [ str , int ]]: return [{ 'name' : name, 'age' : age}] print (GetData( 'Sandeep Jain' , 35 )) |
Output:
[{'name': 'Sandeep Jain', 'age': 35}]
Example 2:
In this example, we are using list comprehension to get a List of Dictionary.
Python3
# import library from typing import List , Dict # define function def get_list_of_dicts(name: str , category: str ) - > Dict [ str , str ]: return [{ 'name' : name, 'category' : category}] Fruit = [ "Mango" , "tomato" , "potato" , "papaya" ] Fruit_type = [ "fruit" , "vegetable" , "vegetable" , "fruit" ] res = [get_list_of_dicts(Fruit[i], Fruit_type[i]) for i in range ( 3 )] print (res) |
Output:
[[{‘name’: ‘a’, ‘surname’: 1}], [{‘name’: ‘b’, ‘surname’: 2}], [{‘name’: ‘c’, ‘surname’: 3}]]