Create Dictionary Iteratively in Python

This tutorial will discuss about unique ways to create dictionary iteratively in Python.

Table Of Contents

Create & Initialize Dictionary in a Loop with range() method

We can create an empty dictionary, and initialize it in a loop. Suppose we have two list i.e. list of keys and list of values i.e.

keys = ['Ritika', 'Smriti', 'Mathew', 'Justin']
values = [34, 41, 42, 38]

Both the lists are of same size. Now to initialize a Dictionary in loop, with these two lists, follow the folloiwng step,

  • Create an empty Dictionary.
  • Iterate from number 0 till N, where N is the size of lists.
  • During loop, for each number i, fetch values from both the lists at ith index.
  • Add ith key and ith value from lists as a key-value pair in the dictionary using [] operator.

Let’s see the complete example,

# A List of Keys
keys = ['Ritika', 'Smriti', 'Mathew', 'Justin']

# A List of Values
values = [34, 41, 42, 38]

# Initialize an empty dictionary
students = {}

# Add key-value pairs iteratively using a for loop
for i in range(len(keys)):
    # Fetch item at ith index from Keys list
    key = keys[i]
    # Fetch item at ith index from Values list
    value = values[i]
    students[key] = value

# Print the resulting dictionary
print(students)

Output

{'Ritika': 34, 'Smriti': 41, 'Mathew': 42, 'Justin': 38}

Create & Initialize Dictionary in a Loop with zip() method

Create a sequence of zipped tuples from two lists using the zip() method. Pass both the lists in the zip() method, and it will give us a list of tuples, where each ith value in tuple contains the ith value from both the list.

Iterate over the zipped sequence using a for loop, and for each entry create a key-value pair in the dictionary.

Let’s see the complete example,

# A List of Keys
keys = ['Ritika', 'Smriti', 'Mathew', 'Justin']

# A List of Values
values = [34, 41, 42, 38]

# Initialize an empty dictionary
students = {}

# Add key-value pairs iteratively using a for loop
for key, value in zip(keys, values):
    students[key] = value

# Print the resulting dictionary
print(students)

Output

{'Ritika': 34, 'Smriti': 41, 'Mathew': 42, 'Justin': 38}

Summary

We learned about two ways to create a Dictionary in Loop in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top