Tuple to Dictionary in PythonIn this tutorial, we will discuss how we can convert a tuple to a dictionary in Python. We know that the elements of tuples are enclosed within parentheses and the elements of a dictionary are present in the form of a key-value pair and are enclosed within curly brackets. We will use the following techniques to convert a tuple to a dictionary in Python-
Let’s get started with the first one, Using setdefault()The function of setdefault() is to return the value associated with a key and if the key is not present it is inserted with a default value. The following program illustrates how it can be used in a Python program. Output: The converted dictionary is: {'English': [2001], 'Hindi': [2002], 'Mathematics': [2003], 'Computer Science': [2004], 'Physics': [2005], 'Chemistry': [2006]} Explanation-
In the second program, we will learn how dict() can be used for the same. Using dict()The dict() is used to create a dictionary in Python, let’s see how it can add meaning to our program. Consider the program given below, Output: The converted dictionary is: {'English': 2001, 'Hindi': 2002, 'Mathematics': 2003, 'Computer Science': 2004, 'Physics': 2005, 'Chemistry': 2006} Explanation-
In the third program, we will see how dictionary comprehension can help us. Using Dictionary ComprehensionThe program below shows the same, Output: The values in sub_names are: ('English', 'Hindi', 'Mathematics', 'Computer Science', 'Physics', 'Chemistry') The values in sub_codes are: (2001, 2002, 2003, 2004, 2005, 2006) The resultant dictionary is: {'English': 2001, 'Hindi': 2002, 'Mathematics': 2003, 'Computer Science': 2004, 'Physics': 2005, 'Chemistry': 2006} Explanation-
In the last program, we will learn how zip() and dict() can be used in the Python program. Using zip() and dict()We have understood how the dict() works, here we will be applying both dict() and zip(), the zip() method takes the iterable items and appends them to form a single tuple. The following program illustrates the same- Output: The values in sub_names are: ('English', 'Hindi', 'Mathematics', 'Computer Science', 'Physics', 'Chemistry') The values in sub_codes are: (2001, 2002, 2003, 2004, 2005, 2006) The resultant dictionary is: {'English': 2001, 'Hindi': 2002, 'Mathematics': 2003, 'Computer Science': 2004, 'Physics': 2005, 'Chemistry': 2006} Explanation-
ConclusionIn this tutorial, we learned the different methods of converting a tuple to a dictionary in Python. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263360.html