JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Saving a dictionary to a file in Python

Author:JIYIK Last Updated:2025/05/06 Views:

This tutorial explains various ways to save dictionaries to files using Python. The methods include:

  • The Python picklemodule's dump()function.
  • NumPyFunctions of the library save().
  • Functions of Python jsonmodules .dump()

In Python, use the function pickleof the module dumpto save the dictionary to a file

The following code example shows how we can use the save function pickleof the module dump()to save a dictionary and load()read the dictionary from the saved file using the read function. The save function pickleof the module dump()requires the dictionary we want to save and a file object as arguments in order to save the dictionary as .pkla file.

import pickle

my_dict = {"Apple": 4, "Banana": 2, "Orange": 6, "Grapes": 11}

with open("myDictionary.pkl", "wb") as tf:
    pickle.dump(my_dict, tf)

The following code example shows how to use load()the function to read a dictionary saved in a file. load()The function requires a file object as a parameter .pklto load a dictionary from a file.

import pickle

with open("myDictionary.pkl", "wb") as tf:
    new_dict = pickle.load(tf)

print(new_dict.item())

Output:

{ 'Apple': 4, 'Banana': 2, 'Orange': 6, 'Grapes': 11}

In Python, use NumPythe library's savefunction to save a dictionary to a file.

NumPyThe library's save()save function can also save the dictionary in a file. To save the dictionary to .npya file, save()the function requires as parameters the name of the file we want to save and the dictionary to save to the file.

Code example:

import numpy as np

my_dict = {"Apple": 4, "Banana": 2, "Orange": 6, "Grapes": 11}
np.save("file.npy", my_dict)

This code example shows how to read .npya Python dictionary saved as a .txt file. NumPyThe library's load().txt function requires a file name and allow_picklethe .txt parameter needs to be set to .txt in order to load a saved dictionary Truefrom a .txt file..npy

Code example:

import numpy as np

new_dict = np.load("file.npy", allow_pickle="TRUE")
print(new_dict)

In Python, use the function jsonof the module dumpto save a dictionary to a file.

Another way to save a dictionary to a file in Python is by using the save function jsonof the module dump(). It also takes as arguments the variable we want to save dictand the file object to save the dictionary to .jsona file.

Sample code:

import json

my_dict = {"Apple": 4, "Banana": 2, "Orange": 6, "Grapes": 11}

tf = open("myDictionary.json", "w")
json.dump(my_dict, tf)
tf.close()

The following is a code example of using the function jsonof the module loadto read a dictionary saved as a file. load()The function requires a file object as a parameter and .jsonloads a dictionary from the file.

import json

tf = open("myDictionary.json", "r")
new_dict = json.load(tf)
print(new_dict)

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Writing logs to a file in Python

Publish Date:2025/05/06 Views:132 Category:Python

This tutorial will show you how to write logs to files in Python. Use the module in Python logging to write logs to files Logging is used to debug a program and find out what went wrong. logging The log module is used to log data to a file

Comparing two dates in Python

Publish Date:2025/05/06 Views:97 Category:Python

This tutorial explains how to compare two dates in Python. There are multiple ways to determine which date is greater, so the tutorial also lists different sample codes to illustrate the different methods. Comparing two dates in Python usin

Reload or unimport modules in Python

Publish Date:2025/05/06 Views:58 Category:Python

Modules allow us to store definitions of different functions and classes in Python files, which can then be used in other files. pandas , NumPy , scipy , Matplotlib are the most widely used modules in Python. We can also create our own modu

Pausing program execution in Python

Publish Date:2025/05/06 Views:156 Category:Python

This tutorial will demonstrate various ways to pause a program in Python. Pausing the execution of a program or application is used in different scenarios, such as when a program requires user input. We may also need to pause the program fo

Importing modules from a subdirectory in Python

Publish Date:2025/05/06 Views:190 Category:Python

This tutorial will explain various ways to import modules from subdirectories in Python. Suppose we have a file in a subdirectory of our project directory and we want to import this file and use its methods in our code. We can import files

Sleeping for a number of milliseconds in Python

Publish Date:2025/05/06 Views:124 Category:Python

In this tutorial, we will look at various ways to pause or suspend the execution of a program in Python for a given amount of time. Let's say we want to pause the execution of a program for a few seconds to let the user read instructions ab

Python Numpy.pad Function

Publish Date:2025/05/06 Views:104 Category:Python

In Python, we have NumPy the array module to create and use arrays. Arrays can have different sizes and dimensions. Padding is a useful method that can be used to compensate for the size of an array. We can mutate an array and add some padd

Generating Random Colors in Python

Publish Date:2025/05/06 Views:135 Category:Python

In the digital world, colors are represented in different formats. RGB, Hexadecimal format are just some of the commonly used formats. In this tutorial, we will learn how to generate random colors in Python. When we talk about generating ra

Getting the name of a class in Python

Publish Date:2025/05/06 Views:83 Category:Python

Just like object constructors, classes can be defined as user-defined prototypes for creating objects. class Classes can be created using the keyword . A class is a data structure that can contain both data members and member methods. This

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial