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.
- Python | Count occurrences of each word in given text file (Using dictionary)
- Count number of lines in a text file in Python
- Python program to extract Email-id from URL text file
- Convert Text and Text File to PDF using Python
- Python | Count the Number of matching characters in a pair of string
- Convert Text file to JSON in Python
- Python | Scramble words from a text file
- Saving Text, JSON, and CSV to a File in Python
- Extract numbers from a text file and add them using Python
- Python | Create an empty text file with current date as its name
- Python program to reverse the content of a file and store it in another file
- Python | Count occurrences of a character in string
- Python | Count occurrences of an element in a Tuple
- Python | Count occurrences of an element in a list
- Python | Count String occurrences in mixed list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.