Home  >  Article  >  Backend Development  >  How to Store and Retrieve Python Dictionaries: JSON vs. Pickle?

How to Store and Retrieve Python Dictionaries: JSON vs. Pickle?

DDD
DDDOriginal
2024-10-27 08:45:31403browse

How to Store and Retrieve Python Dictionaries: JSON vs. Pickle?

Storing Python Dictionaries

Preserving dictionaries in files for future retrieval is a practical need for various applications. This article explores two methods for storing and loading dictionaries: JSON and pickle.

JSON

JSON stands for JavaScript Object Notation and is a popular format for data exchange. The json module in Python provides methods for converting Python objects, including dictionaries, to JSON strings and vice versa.

To save a dictionary to a JSON file, use json.dump() with the file object as the first argument:

<code class="python">import json

data = {'key1': "keyinfo", 'key2': "keyinfo2"}

with open('data.json', 'w') as fp:
    json.dump(data, fp)</code>

To load the dictionary back into the program:

<code class="python">with open('data.json', 'r') as fp:
    data = json.load(fp)</code>

JSON allows for additional arguments, such as sort_keys and indent, to control the output format.

Pickle

Pickle is Python's native serialization module. It converts objects, including dictionaries, to a byte stream for storage.

To save a dictionary using pickle:

<code class="python">import pickle

with open('data.p', 'wb') as fp:
    pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL)</code>

The protocol argument specifies the serialization format.

To load the pickled dictionary:

<code class="python">with open('data.p', 'rb') as fp:
    data = pickle.load(fp)</code>

Both JSON and pickle offer convenient ways to store and retrieve dictionaries in files. Choose the method that best suits your requirements for data exchange or persistence.

The above is the detailed content of How to Store and Retrieve Python Dictionaries: JSON vs. Pickle?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn