Python program to Count the Number of occurrences of a key-value pair in a text file
Given a text file of key-value pairs. The task is to count the number of occurrences of the key-value pairs in the file.
Input File: Coin:H Coin:T Coin:H Coin:H Coin:H Coin:T Coin:H Coin:T Coin:H Coin:H Output: The count of coin:h is 7 The count of coin:t is 3 Input File: geeks:G for:F geeks:G geeks:G geek:H for:F geek:H Output: The count of geeks:g is 3 The count of for:f is 2 The count of geek:h is 2
The approach is very simple. Maintain another dictionary (say d) that will store the count of occurrence of each key-value pair of the file. Store the key-value pair of the text file as a key in the dictionary. Now iterate through the key-value pairs of the file. If the pair is present in the dictionary then increment the value of that pair by one otherwise insert the pair and set its value to one.
Below is the implementation.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course