Open In App

How to Initialize a Dictionary in Python Using For Loop

Last Updated : 22 Jan, 2024
Comments
Improve
Suggest changes
4 Likes
Like
Report

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.

Here, we are explaining ways to Initialize a Dictionary in Python Using the For Loop following.

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.

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.

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.

Output :

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Next Article

Similar Reads