Program to count the number of occurrence of key-value pair in a text file using Python

Introduction

The task is to count the occurrence of key-value pairs for the text in the given file.

Input File: demo.txt

to:t
welcome:w
welcome:w
gocoding:w

The above file is called from the program.

Program

file= open("demo.txt", "r") 
dct = dict() 
 
for temp in file: 
    temp = temp.strip() 
    temp = temp.lower() 
    readLine = temp.split() 
    for i in readLine: 
        if i in dct: 
            dct[i] = dct[i]+1
        else: 
            dct[i] = 1
 
file.close() 
print("Count of: ")
for k in list(dct.keys()): 
    print("{} is {}".format(k,dct[k]))

Output

Program to count the number of occurrence Output

Explanation

Approach:

  • Store key-value pair as key in dictionary.
  • Iterate through each value:
    • Increment by 1 if already present.
    • Insert value if not present in dictionary and set value to 1.

Leave a comment

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