This tutorial will discuss about unique ways to create a dictionary from list in Python.
Table Of Contents
Using Dictionary Comprehension
Suppose we have a list of strings, and we want to create a dictionary from these keys.
We can iterate over the string in list, inside the dictionary comprehension. For each string we will make it as the key in a key-value pair, and the value in that pair will be the length of that string key.
All this will be done in a single line usng Dictionary Comprehension.
Let’s see the complete example,
listOfKeys = ['John', 'Avisha', 'Varun', 'Riti'] # Create a Dictionary from a List dictObj = {item: len(item) for item in listOfKeys} print(dictObj)
Output
Frequently Asked:
{'John': 4, 'Avisha': 6, 'Varun': 5, 'Riti': 4}
Using a For-Loop
Now if you don’t want to use the dictionary comprehension, then we can do the same thing using a simple for loop.
Iterate about all the strngs in the list and for each string in the list, add it as a key in the dictionary and assign the value as a length of this string item.
the value field will be the number of characters in this string key. So when the for loop end, we will have a dictionary, where each item of the dictionary will have a key from the list and its value will be the number of characters in the key string.
Let’s see the complete example,
listOfKeys = ['John', 'Avisha', 'Varun', 'Riti'] dictObj = {} for item in listOfKeys: dictObj[item] = len(item) print(dictObj)
Output
{'John': 4, 'Avisha': 6, 'Varun': 5, 'Riti': 4}
Summary
We learned about two different wasy to create a Dictionary from a List in python.