Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python program to Count the Number of occurrences of a key-value pair in a text file
Next article icon

Python program to Count the Number of occurrences of a key-value pair in a text file

Last Updated : 06 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 with Python

Program to Count the occurrences of a key-value pair

  • Naive Approach to Count the Occurrences of a key-value Pair
  • Using Python built-in collections.Counter
  • Using regular expressions (re module)

Text file:

python-key-value-pair

Naive Approach to Count the Occurrences of a key-value Pair

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
# opening text file f = open("file.txt", "r") d = dict()  for res in f:     # removing new line and extra     # space characters     res = res.strip()      # changing ase to prevent matching     # errors     res = res.lower()      # separating key-value pairs     lines = res.split()      for line in lines:          if line in d:              # If the key-value pair             # is present in d then              # increment its value by one             d[line] = d[line]+1         else:              # Insert the key-value pair             # in the dictionary and sets             # its value to one             d[line] = 1  f.close()  # Printing Result for key in list(d.keys()):     print("The count of {} is {}".format(key,d[key])) 

Output : python-key-valiu-pair-output

Time complexity: O(n*m), where n is the number of lines in the text file and m is the number of words in each line.
Auxiliary space: O(k), where k is the number of unique key-value pairs in the text file.

Count Occurrences of a Value in a Python Dictionary using collections.Counter

This method utilizes the collections.Counter class, which is a powerful tool for counting occurrences of elements in a collection.

Python
from collections import Counter  def count_key_value_pairs(file_path, key, value):     with open(file_path, 'r') as file:         lines = file.readlines()      count = 0     for line in lines:         # Assuming the key-value pairs are separated by '=' and there are no spaces around '='         line_key, line_value = line.strip().split('=')         if line_key == key and line_value == value:             count += 1      return count  if __name__ == "__main__":     file_path = "path/to/your/text_file.txt"     key_to_find = "your_key"     value_to_find = "your_value"      occurrences = count_key_value_pairs(file_path, key_to_find, value_to_find)     print(f"Number of occurrences of '{key_to_find}={value_to_find}': {occurrences}") 

Output:

python-key-valiu-pair-output

Time complexity: of O(N * K)
Space complexity: of O(N)

Count Occurrences of a Value in a Python Dictionary using RegEx

This method utilizes the re module to search for key-value pairs in the text file using regular expressions.

Python
import re  def count_key_value_pairs(file_path, key, value):     with open(file_path, 'r') as file:         data = file.read()      pattern = r'\b{}={}\b'.format(re.escape(key), re.escape(value))     occurrences = len(re.findall(pattern, data))      return occurrences  if __name__ == "__main__":     file_path = "path/to/your/text_file.txt"     key_to_find = "your_key"     value_to_find = "your_value"      occurrences = count_key_value_pairs(file_path, key_to_find, value_to_find)     print(f"Number of occurrences of '{key_to_find}={value_to_find}': {occurrences}") 

Output:

python-key-valiu-pair-output

Time complexity: O(N)
Space complexity: O(N).


Next Article
Python program to Count the Number of occurrences of a key-value pair in a text file

V

vanshikagoyal43
Improve
Article Tags :
  • Python
  • Python Programs
  • python-file-handling
  • Python dictionary-programs
  • Python file-handling-programs
Practice Tags :
  • python

Similar Reads

    Python Program to Find the Number of Unique Words in Text File
    Given a text file, write a python program to find the number of unique words in the given text file in Python.Examples:Input: gfg.txtOutput: 18Contents of gfg.txt: GeeksforGeeks was created with a goal in mind to provide well written well thought and wellexplained solutions for selected questionsExp
    2 min read
    Python - Count occurrences of each word in given text file
    Many times it is required to count the occurrence of each word in a text file. To achieve so, we make use of a dictionary object that stores the word as the key and its count as the corresponding value. We iterate through each word in the file and add it to the dictionary with a count of 1. If the w
    4 min read
    Python - Find occurrences for each value of a particular key
    Given a List of dictionaries, for a particular key, find the number of occurrences for each value of that key. Input : test_list = [{'gfg' : 3, 'best' : 4}, {'gfg' : 3, 'best' : 5}, {'gfg' : 4, 'best' : 4}, {'gfg' : 7, 'best' : 4} ], K = 'gfg' Output : [{3: 2}, {4: 1}, {7: 1}] Explanation : gfg has
    6 min read
    Python program to unique keys count for Value in Tuple List
    Given dual tuples, get a count of unique keys for each value present in the tuple. Input : test_list = [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)] Output : {4: 4, 2: 3, 1: 2} Explanation : 3, 2, 8 and 10 are keys for value 4. Input : test_list = [(3, 4), (1, 2), (8, 1),
    6 min read
    Python | Count occurrence of all elements of list in a tuple
    Given a tuple and a list as input, write a Python program to count the occurrences of all items of the list in the tuple. Examples: Input : tuple = ('a', 'a', 'c', 'b', 'd') list = ['a', 'b'] Output : 3 Input : tuple = (1, 2, 3, 1, 4, 6, 7, 1, 4) list = [1, 4, 7] Output : 6 Approach #1 : Naive Appro
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences