Python combine two list to dictionary
Convert two lists into a dictionary in PythonPythonServer Side ProgrammingProgramming While a Python list contains a series of values a dictionary on the other hand contains a pair of values which are called key-value pairs. In this article we will take two lists and mark them together to create a Python dictionary. Show With for and removeWe create two nested for loops. In the inner loop will assign one of the list as key for the dictionary while keep removing the values from the list which is outer for loop. ExampleLive Demo listK = ["Mon", "Tue", "Wed"] listV = [3, 6, 5] # Given lists print("List of K : ", listK) print("list of V : ", listV) # Empty dictionary res = {} # COnvert to dictionary for key in listK: for value in listV: res[key] = value listV.remove(value) break print("Dictionary from lists :\n ",res)OutputRunning the above code gives us the following result With for and rangeThe two lists are combined to create a pair of values by putting them into a for loop. The range and len functions are used to keep track of the number of elements till all the key value pairs are created. ExampleLive Demo OutputRunning the above code gives us the following result ('List of K : ', ['Mon', 'Tue', 'Wed']) ('list of V : ', [3, 6, 5]) ('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})With zipThe zip function does something similar to above approach. It also combines the elements from the two lists, creating key and value pairs. ExampleLive Demo listK = ["Mon", "Tue", "Wed"] listV = [3, 6, 5] # Given lists print("List of K : ", listK) print("list of V : ", listV) # COnvert to dictionary res = dict(zip(listK, listV)) print("Dictionary from lists :\n ",res)OutputRunning the above code gives us the following result ('List of K : ', ['Mon', 'Tue', 'Wed']) ('list of V : ', [3, 6, 5]) ('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})Pradeep Elance Published on 04-Jun-2020 11:14:48 Previous Page Print Page Next Page Advertisements |