How to Create a Dictionary in Python Using a For Loop?

In this tutorial, I will explain how to create a dictionary in Python using a for loop. As developers, we come across working with dictionaries and it is very important to know the creation of a dictionary using for loop. By using a for loop, you can dynamically generate dictionary items based on certain conditions or iterate over existing data. Let us learn more about this topic today.

Python Dictionaries

Before getting into creating a dictionary with a for loop, let’s quickly review what dictionaries are in Python. A dictionary is an unordered collection of key-value pairs, where each key is unique. You can create a dictionary by placing comma-separated key-value pairs inside curly braces {}. For example:

person = {"name": "John", "age": 30, "city": "New York"}

In this example, we have a dictionary called person with keys “name”, “age”, and “city”, and their corresponding values.

Read How to Sum All Values in a Python Dictionary?

Create a Dictionary in Python Using a For Loop

Now, let’s explore how we can create a Python dictionary using a for loop. Suppose you have a list of names and you want to create a dictionary where each name is a key and the value is the length of the name. Here’s an example:

names = ["Emily", "Michael", "Jessica", "Christopher"]
name_lengths = {}

for name in names:
    name_lengths[name] = len(name)

print(name_lengths)

Output:

{'Emily': 5, 'Michael': 7, 'Jessica': 7, 'Christopher': 11}

I executed the above example code and added the screenshot.

Create a Dictionary in Python Using a For Loop

In this example, we start with a list of names. We create an empty dictionary called name_lengths to store the name-length pairs. We then use a for loop to iterate over each name in the names list. Inside the loop, we add a new key-value pair to the name_lengths dictionary, where the key is the name and the value is the length of the name obtained using the len() function.

Check out Write a Python Program to Remove Duplicates From a Dictionary

Example: Count Word Frequencies

Let’s consider a real-world scenario where you have a paragraph of text and you want to count the frequency of each word. You can use a dictionary and a for loop to accomplish this task. Here’s an example:

paragraph = "The United States of America, commonly known as the United States or America, is a country primarily located in North America. It consists of 50 states, a federal district, five major unincorporated territories, 326 Indian reservations, and nine minor outlying islands."

word_counts = {}

# Split the paragraph into individual words
words = paragraph.split()

# Count the frequency of each word
for word in words:
    word = word.lower()
    if word in word_counts:
        word_counts[word] += 1
    else:
        word_counts[word] = 1

print(word_counts)

Output:

{'the': 2, 'united': 2, 'states': 2, 'of': 2, 'america,': 1, 'commonly': 1, 'known': 1, 'as': 1, 'or': 1, 'america': 1, 'is': 1, 'a': 2, 'country': 1, 'primarily': 1, 'located': 1, 'in': 1, 'north': 1, 'america.': 1, 'it': 1, 'consists': 1, '50': 1, 'states,': 1, 'federal': 1, 'district,': 1, 'five': 1, 'major': 1, 'unincorporated': 1, 'territories,': 1, '326': 1, 'indian': 1, 'reservations,': 1, 'and': 1, 'nine': 1, 'minor': 1, 'outlying': 1, 'islands.': 1}

I executed the above example code and added the screenshot.

How to Create a Dictionary in Python Using a For Loop

In this example, we have a paragraph about the United States. We create an empty dictionary called word_counts to store the word frequencies. We split the paragraph into individual words using the split() method. Then, we use a for loop to iterate over each word. For each word, we convert it to lowercase using lower() to ensure case-insensitive counting.

Inside the loop, we check if the word already exists as a key in the word_counts dictionary. If it does, we increment its corresponding value by 1. If it doesn’t exist, we add a new key-value pair to the dictionary with an initial count of 1.

Read How to Search in Dictionary By Value in Python

Conclusion

In this tutorial, I explained how to create a dictionary in Python using a for loop. I discussed what are Python dictionaries, and creating a dictionary in Python using for loop. I also covered a real-time example of counting word frequencies.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.