Contents Show
Python List to DictionaryThere are many ways in which you can interpret the data in list as keys and values, and convert this list into a dictionary. Some of the formats of lists are
Also, some of the other scenarios are:
In this tutorial, we will learn how to convert these formats of list to dictionary, with the help of well detailed example programs. Example 1: Convert List to DictionaryIn this example, we will convert the list of format [key_1, value_1, key_2, value_2, ] to dictionary of {key_1:value_1, key_2:value_2, }. We will use dictionary comprehension to convert this type of list to dictionary. Python Program myList = ['a', 'apple', 'b', 'banana', 'c', 'cherry'] myDict = {myList[i]: myList[i + 1] for i in range(0, len(myList), 2)} print(myDict) RunOutput {'a': 'apple', 'b': 'banana', 'c': 'cherry'}Example 2: Convert Lists of Keys and Values to DictionaryIn this example, we will convert a list of format [(key_1, value_1), (key_2, value_2), ] to dictionary of {key_1:value_1, key_2:value_2, }. We will use dictionary comprehension to convert this lists of keys and values to dictionary. Python Program listKeys = ['a', 'b', 'c'] listValues = ['apple', 'banana', 'cherry'] myDict = {listKeys[i]: listValues[i] for i in range(0, len(listKeys), 1)} print(myDict) RunOutput {'a': 'apple', 'b': 'banana', 'c': 'cherry'}Example 3: Convert List of Tuples to DictionaryIn this example, we will convert a list of format [(key_1, value_1), (key_2, value_2), ] to dictionary of {key_1:value_1, key_2:value_2, }. We will use dictionary comprehension to convert list of tuples to dictionary. Python Program myList = [('a', 'apple'), ('b', 'banana'), ('c', 'cherry')] myDict = {myList[i][0]: myList[i][1] for i in range(0, len(myList), 1)} print(myDict) RunOutput {'a': 'apple', 'b': 'banana', 'c': 'cherry'}Example 4: Convert List of Dictionary with Index as ValueIn this example, we will convert a list of format [key_1, key_2, ] to dictionary of {key_1:0, key_2:1, }. Python Program myList = ['a', 'b', 'c'] myDict = {myList[i]: i for i in range(0, len(myList), 1)} print(myDict) RunOutput {'a': 0, 'b': 1, 'c': 2}Example 5: Convert List of Dictionary with Default ValueIn this example, we will convert a list of format [key_1, key_2, ] to dictionary of {key_1:default_value, key_2:default_value, }. Python Program myList = ['a', 'b', 'c'] defaultValue = 54 myDict = {myList[i]: defaultValue for i in range(0, len(myList), 1)} print(myDict) RunOutput {'a': 54, 'b': 54, 'c': 54}SummaryIn this tutorial of Python Examples, we learned how to convert a Python List to Dictionary. Related Tutorials
|