- Python : How to unpack list, tuple or dictionary to Function arguments using * & **
- Frequently Asked:
- Unpack elements in list or tuple to function arguments using *
- Unpack elements in dictionary to function arguments using **
- Related posts:
- How to Unpack Dictionary in Python
- Dictionaries in Python
- How to Unpack Dictionary in Python
- Using the Unpack Operator ( ** ) to Unpack Dictionary in Python
- Further reading:
- Using the for Loop to Unpack Dictionary in Python
- Using the iteritems() Function to Unpack Dictionary in Python
- Using the items() Function to Unpack Dictionary in Python
- Using the keys and values Functions to Unpack Dictionary in Python
- Conclusion
Python : How to unpack list, tuple or dictionary to Function arguments using * & **
In this article we will discuss how to unpack a list, tuple and dictionary to function arguments.
Suppose we have a function with 3 parameters i.e.
def updateStudentDetail(name, phone, address): print("**********************") print("Student Name : ", name) print("Student phone : ", phone) print("Student address : ", address)
We can call this function and pass three arguments like this,
updateStudentDetail("Riti", "3343" , "Delhi")
But many times we want to pass arguments which are in some other objects like in list or tuple or dictionary to function. We can automatically unpacking the elements in these objects instead of accessing them individually and passing them to function. Let’s see how to do that,
Frequently Asked:
Unpack elements in list or tuple to function arguments using *
Python provides a symbol * , on prefixing this with list will automatically unpack the list elements to function arguments. For example,
Suppose we have a list of ints i.e.
details = ["Riti", "3343" , "Delhi"]
Let’s unpack this list elements to function arguments by symbol * i.e.
# Auto unpack elements in list to function arguments with * updateStudentDetail(*details)
Output of the function will be,
Student Name : Riti Student phone : 3343 Student address : 3343
On similar line we can use tuple with * to unpack its elements to function arguments too i.e.
# A tuple details = ("Riti", "3343" , "Delhi")
Output of the function will be,
Student Name : Riti Student phone : 3343 Student address : Delhi
But we need to make sure that elements in list or tuple are exactly equal to function parameters. Otherwise it will cause error. Therefore its generally used with functions that accepts variable length arguments i.e.
def calculateAverage(*args): ''' Function that accept variable length arguments ''' num = len(args) if num == 0: return 0; sumOfNumbers = 0 for elem in args: sumOfNumbers += elem return sumOfNumbers / num
This function can accept n number of arguments. Now lets pass different size lists to this function and automatically unpack them i.e
list1 = [1,2,3,4,5,6,7,8] list2 = [1,2,3,4,5] list3 = [1,2,3] avg = calculateAverage( *list1) print("Average = " , avg) avg = calculateAverage(*list2) print("Average = " , avg) avg = calculateAverage(*list3) print("Average = " , avg)
Average = 4.5 Average = 3.0 Average = 2.0
Unpack elements in dictionary to function arguments using **
Python provides an another symbol ** . On prefixing it with a dictionary, all the key value pairs in dictionary will be unpacked to function arguments. Let’s understand this by an example,
As we have a function that accepts 3 parameters i.e.
def updateStudentDetail(name, phone, address): print("**********************") print("Student Name : ", name) print("Student phone : ", phone) print("Student address : ", address)
and a dictionary whose key are with same name as function parameters i.e.
As keys in dictionary are of same name as function arguments, so applying symbol ** on this dictionary will unpack all the values to function arguments i.e.
# Auto unpack dictionary to function arguments with ** updateStudentDetail(**details)
Student Name : Sam Student phone : 112 Student address : London
But we need to make sure that key names are same as function parameter names, also their count should be same too. Otherwise unpacking will cause Error. Therefore, its generally use with function that accepts variable length key value pairs in arguments i.e.
def updateDetails(**kwargs): ''' Function that accept variable length key value pairs ''' print("**********************") if 'name' in kwargs : print("Student Name : ", kwargs['name']) if 'phone' in kwargs : print("Student phone : ", kwargs['phone']) if 'address' in kwargs : print("Student address : ", kwargs['address'])
This can accept variable length key value pair as arguments. Let’s pass different size dictionaries to this function with auto unpacking using **,
details = < 'name' : 'Sam' , 'phone' : '112' ># Auto unpack dictionary to function arguments with ** updateDetails(**details)
Student Name : Sam Student phone : 112
details = < 'name' : 'Sam' , 'section' : 'A' , 'address' : 'London' , 'phone' : '112' ># Auto unpack dictionary to function arguments with ** updateDetails(**details)
Student Name : Sam Student phone : 112 Student address : London
Complete example is as follows,
def updateStudentDetail(name, phone, address): print("**********************") print("Student Name : ", name) print("Student phone : ", phone) print("Student address : ", address) def calculateAverage(*args): ''' Function that accept variable length arguments ''' num = len(args) if num == 0: return 0; sumOfNumbers = 0 for elem in args: sumOfNumbers += elem return sumOfNumbers / num def updateDetails(**kwargs): ''' Function that accept variable length key value pairs ''' print("**********************") if 'name' in kwargs : print("Student Name : ", kwargs['name']) if 'phone' in kwargs : print("Student phone : ", kwargs['phone']) if 'address' in kwargs : print("Student address : ", kwargs['address']) if __name__ == '__main__': updateStudentDetail("Riti", "3343" , "Delhi") print("****** Unpack a List to Function Arguments ******") details = ["Riti", "3343" , "Delhi"] updateStudentDetail(details[0], details[1] , details[1]) # Auto unpack elements in list to function arguments with * updateStudentDetail(*details) print("****** Unpack a tuple to Function Arguments ******") details = ("Riti", "3343" , "Delhi") # Auto unpack elements in tuple to function arguments with * updateStudentDetail(*details) print("****** Unpack Lists of different size to Function Arguments ******") list1 = [1,2,3,4,5,6,7,8] list2 = [1,2,3,4,5] list3 = [1,2,3] avg = calculateAverage( *list1) print("Average = " , avg) avg = calculateAverage(*list2) print("Average = " , avg) avg = calculateAverage(*list3) print("Average = " , avg) print("****** Unpack a dictionary to Function Arguments ******") details = < 'name' : 'Sam' , 'phone' : '112' , 'address' : 'London' ># Auto unpack dictionary to function arguments with ** updateStudentDetail(**details) print("****** Unpack a different size dictionaries to Function Arguments ******") details = < 'name' : 'Sam' , 'phone' : '112' ># Auto unpack dictionary to function arguments with ** updateDetails(**details) details = < 'name' : 'Sam' , 'section' : 'A' , 'address' : 'London' , 'phone' : '112' ># Auto unpack dictionary to function arguments with ** updateDetails(**details)
********************** Student Name : Riti Student phone : 3343 Student address : Delhi ****** Unpack a List to Function Arguments ****** ********************** Student Name : Riti Student phone : 3343 Student address : 3343 ********************** Student Name : Riti Student phone : 3343 Student address : Delhi ****** Unpack a tuple to Function Arguments ****** ********************** Student Name : Riti Student phone : 3343 Student address : Delhi ****** Unpack Lists of different size to Function Arguments ****** Average = 4.5 Average = 3.0 Average = 2.0 ****** Unpack a dictionary to Function Arguments ****** ********************** Student Name : Sam Student phone : 112 Student address : London ****** Unpack a different size dictionaries to Function Arguments ****** ********************** Student Name : Sam Student phone : 112 ********************** Student Name : Sam Student phone : 112 Student address : London
Related posts:
How to Unpack Dictionary in Python
In this article, we will see how to unpack dictionary in Python.
Dictionaries in Python
A dictionary is one of the fundamental data structures of Python. It stores its elements as key-value pairs and has evolved with time. In recent versions of Python, dictionaries use hash functions which make accessing values from keys a fast process and are also known to retain the order of elements.
Python uses the dict class that represents dictionaries as the base for many other objects so many operations are possible with them. We can unpack dictionaries as well.
Unpacking a dictionary means unloading and printing the key-value pairs or loading them in other objects like a tuple or a list. We also unpack a dictionary while sending their values to a function or when we are merging two dictionaries.
For this, we have the unpack operator in Python and loads of various functions that can be utilized.
How to Unpack Dictionary in Python
We will now discuss different ways how to unpack dictionary in Python.
Using the Unpack Operator ( ** ) to Unpack Dictionary in Python
The ** operator is used to pack and unpack dictionary in Python and is useful for sending them to a function. This will be made more clear with an example.
In the above example, we have a function that accepts three arguments. We pass these three arguments by packing them in a dictionary using the ** operator.
We can use the ** to unpack dictionaries and merge them in a new dict object.
In the above example, we create a new dictionary by unpacking the contents of the previous dictionary in the new dictionary.
We also have an operator to unpack elements from the list. We can use this operator for dictionaries after converting them to a list of key-value pairs. We will discuss the methods to convert a dictionary to a list of key-value pairs as tuples below and unpack the elements using this operator.
Further reading:
Check if key exists in Dictionary
List of Dictionaries in Python
Using the for Loop to Unpack Dictionary in Python
Dictionaries are iterable in Python. We can use the for loop to iterate by a dictionary and print its contents.
While iterating through a dictionary, we use its keys. We will then use the keys to access the value at every iteration and display them both.
See the following example.
In every iteration, we use the k variable to access the value at the given iteration and display them both.
We can also append them to a list of tuples. For this, we will create an empty list and append the key-value pairs as a tuple in every iteration.
In the above example, we first created an empty list lst and then went on to append the key-value pairs as a tuple using the append() function.
After creating the list, we can unpack the elements using the unpack operator( * ) operator discussed previously.
Using the iteritems() Function to Unpack Dictionary in Python
The iteritems() function was available in Python 2 and it would return the key-value pairs of the dictionary in a view object.
We can use it to unpack dictionary in Python.
This function was replaced by the items() function in Python 3.
Using the items() Function to Unpack Dictionary in Python
The items() function replaced the iteritems() function in Python 3 and returns a better view object of the dictionary backed by the dict class. This function returns an object of type dict_items .
We can use the unpack operator ( * ) for lists with this object.
In the above example, we can observe the type of object returned by the items() function is similar to a list but is backed by the dict class.
This function is also available in Python 2. However, in Python 2, this method directly returns a list of the elements of the dictionary and not a view-object. Any changes made in the dictionary after the items() function call will not be observed in the returned list in Python 2.
Using the keys and values Functions to Unpack Dictionary in Python
The keys() and values() function of the dict class return a view-like object of the keys and values of a dictionary respectively.
We can use these functions with the zip() method to unpack dictionary in Python.
- The zip() method combines the corresponding elements at each position in the view objects.
- This object is converted to a list using the list() function.
- Elements are unpacked from this list using the unpack operator.
Conclusion
To conclude, in this article we discussed dictionaries and how to unpack dictionary in Python. We started by discussing dictionaries and unpack operations in Python. We can use the unpack operators with dictionaries in Python. The ** is directly used for packing and sending a dictionary as a function argument. We can also use this to unpack and merge dictionaries. We also have the unpack operator ( * ) operator that can unpack elements from lists or tuples. To use this, we convert the dictionary to a list of tuples and unpack the elements from this list. Several functions can be used to convert a dictionary to a list and then unpack them.
That’s all about how to unpack dictionary in Python.