How to convert list to dictionary in PythonLists and Dictionaries are two data structure which is used to store the Data. List stores the heterogeneous data type and Dictionary stores data in key-value pair. Here, we are converting the Python list into dictionary. Since list is ordered and dictionary is unordered so output can differ in order. Python list stores the element in the following way. On the other hand, Dictionary is unordered, and stores the unique data. It stores the data in key value pair where each key is associated with it value. Python Dictionary stores the data in following way. In this tutorial, we will learn the conversion Python list to dictionary. Sample Input: Let’s understand the following methods. Method – 1 Using Dictionary ComprehensionWe can convert the list into dictionary using the dictionary comprehension. Let’s understand the following code. Example – Output: {'James': 'Passed', 'Abhinay': 'Passed', 'Peter': 'Passed', 'Bicky': 'Passed'} Explanation – In the above code, we have created a student list to be converted into the dictionary. Using the dictionary compression, we converted the list in dictionary in a single line. The list elements tuned into key and passed as a value. Let’s understand another example. Example – 2 Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100} Explanation: In the above code, we have created square_dict with number-square key/value pair. Method – 2 Using zip() functionThe zip() function is used to zip the two values together. First, we need to create an iterator and initialize to any variable and then typecast to the dict() function. Let’s understand the following example. Example – Output: {'x': 1, 'y': 2, 'z': 3} |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263612.html