Convert list to dictionary Python
In this post, you will learn how to convert a list to a dictionary using the Python programming language.
Python has an in-built dictionary called dict, which we can use to create an arbitrary definition of a character string. It is a collection whose values are accessible by key. The dictionary is a mapping of keys & values. A list is a sequence of indexed and ordered values. It contains a list of any type of data object with a comma separated and enclosed within a square bracket.
Lists are ordered sets of objects, whereas dictionaries are unordered sets. Dictionaries also take up more space in memory due to the hashing process. Both, lists and dictionarys are widely used to store data in Python. During the development process, we may come to the situation where we need to convert a list to a dictionary.
There are some built-in functions and technologies to convert a list to a dictionary using Python. Here, we have mentioned four different ways dictionary comprehension, dict.fromkeys(), zip() or the enumerate() method to convert a list to a dictionary. All these four methods create a new dictionary and they do not modify the existing list.
Convert list to dictionary using dictionary comprehension
Dictionary comprehension is one way to create a dictionary in Python. It creates a dictionary by combining two sets of data, which are in the form of either lists or arrays. It is an elegant and concise way to create dictionaries. List comprehensions use square brackets ([]) whereas Dictionary comprehensions use pointed brackets ({}). In the given example, we convert the list of vegetables into a dictionary using the dictionary comprehension.
First, we initialize a list called vegetables which stores the names that we want to convert into the dictionary. Using the dictionary compression, we change the list in the dictionary in a single line code. The list elements tune into key and pass as a value.
# Create list
vegetables = ["Potato", "Onion", "Tomato", "Cucumber"]
# convert list to dictionary
veg_dict = { veg : "In stock" for veg in vegetables }
# print dictionary
print(veg_dict)
Output of the above code-
{'Potato': 'In stock', 'Onion': 'In stock', 'Tomato': 'In stock', 'Cucumber': 'In stock'}
Convert list to dictionary using zip() method
Python's zip() function creates an iterator that will aggregate elements from at least two iterables. It returns a zip object, which is an iterator of tuples where the main thing in each passed iterator is matched together, and afterward the second thing in each passed iterator is combined together and so on. The zip() method accepts several iterable objects and returns the list of tuples.
# Convert list to dictionary
def listToDict(listx, listy):
zipped_list = zip(listx, listy)
result = dict(zipped_list)
return result
item = ['pizza', 'coffee', 'tea', 'burger', 'noodles']
quantity = [10, 6, 4, 5, 5]
print(listToDict(item, quantity))
Output of the above code -
{'pizza': 10, 'coffee': 6, 'tea': 4, 'burger': 5, 'noodles': 5}
Convert list to dictionary using dict.fromkeys()
Python has a pre-defined fromkeys() method to create a new dictionary from a given sequence of elements. This method accepts a list of keys that you want to turn into a dictionary.
fruits = ["banana", "cherry", "kiwi", "peach"]
fruits_dict = dict.fromkeys(fruits,"In-stock")
print(fruits_dict)
Output of the above code-
{'banana': 'In-stock', 'cherry': 'In-stock', 'kiwi': 'In-stock', 'peach': 'In-stock'}
Convert list to dictionary using Enumerate()
We can use the Python enumerate() method to convert a list into a dictionary with an index as the key and a list item as the value.
veg_list = ["Potato", "Onion", "Tomato", "Cucumber"]
veg_dict = dict(enumerate(veg_list))
print (veg_dict)
Output of the above code-
{0: 'Potato', 1: 'Onion', 2: 'Tomato', 3: 'Cucumber'}
Related Articles
Multiply all elements in list Python
Python program to list even and odd numbers of a list
Python program to print all even numbers between 1 to 100
Find element in list Python
Insert data in MySQL database from an HTML form using Django
Alphabet pattern programs in Python
Python multiline string
glob in Python
Python heap implementation
zip function in Python
Remove last element from list Python
Check if list is empty Python
Remove element from list Python
Python split multiple delimiters
Python loop through list
Python iterate list with index
Python add list to list
Python random choice
Python dict inside list
Remove character from string Python
Python compare two lists