HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat N Strings
      • Python Example Code to Concat 2 Numbers
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
    • Modules and Libraries
      • Python Code to Load .SO File (and Invoke a Function)
      • Python Code for Automation using BDD
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

Python Code to Write & Read Key Value Pair in File

In Python, reading and writing key value pairs to a file is a common task, often done using libraries like JSON.

Reading involves opening a file, loading its contents into a dictionary, and accessing values using keys.

Similarly, writing involves creating a dictionary with key value pairs, converting it to JSON format, and writing it to the file.

Write Key Value Pair to File

First, let me write the Python code that writes key value pairs to a file using the json module.

import json

# Define a dictionary with key value pairs
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Define the file path
file_path = "data.json"

# Write the dictionary to the file
with open(file_path, "w") as file:
    json.dump(data, file)

I’ll explain the code now.

  1. Import the json module to work with JSON data.
  2. Create a dictionary data with key value pairs.
  3. Define the file path where you want to write the data.
  4. Open the file in write mode using open() function.
  5. Use json.dump() function to write the dictionary data to the file in JSON format.

Read Key Value Pair from File

Similar to Write operation, I’ll write now code to read key value pairs from a file.

import json

# Define the file path
file_path = "data.json"

# Read the key value pairs from the file
with open(file_path, "r") as file:
    data = json.load(file)

# Access the values using keys
name = data["name"]
age = data["age"]
city = data["city"]

print("Name:", name)
print("Age:", age)
print("City:", city)

Let me explain you the above code.

  1. Import the json module to work with JSON data.
  2. Define the file path from which you want to read the data.
  3. Open the file in read mode using open() function.
  4. Use json.load() function to load the JSON data from the file into a Python dictionary data.
  5. Access the values in the dictionary using keys.
  6. Use the retrieved values as needed.

Writing and reading key value pair in file is one of the most common requirement especially when you want to manage quick & efficient storage in your project.

Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Python Example Code to Remove Duplicates from a List
  • Example Python Code to interact with databases using libraries like SQLAlchemy
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Python Code to Perform Data Analysis with Pandas

No luck finding what you need? Contact Us

Previously
Python Code to Count and List Files in a Directory
Up Next
In Python File is Not Opening (How to Fix)
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2025 Happiom. All Rights Reserved.