How to Initialize a Dictionary in Python Using For Loop
When you want to create a dictionary with the initial key-value pairs or when you should transform an existing iterable, such as the list into it. You use string for loop initialization. In this article, we will see the initialization procedure of a dictionary using a for loop.
Initialize Python Dictionary Using For Loop
A Dictionary is a collection of the Key-Value Pairs and in the case of Python, these pairs are enclosed by the braces { }. Each value is unique with its corresponding key and this can be a string, number, or even object among the other possible data types. A dictionary can be initiated by first creating it and then assigning it a relationship between the key-value pairs to its existence.
Example 1: Use For loop for Squares
In this example, below Python code initializes an empty dictionary named “squares_dict” then it uses a for loop to populate the dictionary with squares of numbers from 1 to 5 using the print function its prints the resulting dictionary showing the mapping of each number to its square.
Python3
# Initializing an empty dictionary squares_dict = {} # Using a for loop to populate the dictionary for num in range ( 1 , 6 ): squares_dict[num] = num * * 2 # Displaying the initialized dictionary print (squares_dict) |
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Example 2: Initialize From an Existing Iterable
In this example, we can initialize a dictionary using the for loop with the help of main iteration of an older existing iterable like even the list that has the tuples with key-value pairs. This is helpful when you have the information from an another format that might be converted into a dictionary.
Python3
# Example list of the tuples pairs_list = [( 'a' , 1 ), ( 'b' , 2 ), ( 'c' , 3 )] # Initializing a dictionary using a for loop and the list of tuples new_dict = {} for key, value in pairs_list: new_dict[key] = value # Displaying the initialized dictionary print (new_dict) |
Output :
{'a': 1, 'b': 2, 'c': 3}
Example 3: Initialize a Dictionary using List Comprehension
In this example, below Python code initializes a dictionary named “squares_dict_comp” using List Comprehension to Map numbers from 1 to 5 to their squares.
Python3
# Using list comprehension to initialize a dictionary squares_dict_comp = {num: num * * 2 for num in range ( 1 , 6 )} # Displaying the initialized dictionary using the list comprehension print (squares_dict_comp) |
Output :
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Contact Us