Home >Backend Development >Python Tutorial >How do you store Python dictionaries for later use?
Python dictionaries provide a versatile method for organizing data in key-value pairs. To preserve these dictionaries beyond the current program execution, consider storing them as portable files.
Two prevalent options for storing dictionaries are JSON and Pickle. JSON (JavaScript Object Notation) represents data in a human-readable format, while Pickle serializes Python objects into a binary format.
To store a dictionary as a JSON file, use the json module:
<code class="python">import json with open('data.json', 'w') as fp: json.dump(data, fp)</code>
To load the JSON file back into the program:
<code class="python">with open('data.json', 'r') as fp: data = json.load(fp)</code>
Alternatively, use the pickle module to store a dictionary as a pickle file:
<code class="python">import pickle with open('data.p', 'wb') as fp: pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL)</code>
To restore the dictionary from the pickle file:
<code class="python">with open('data.p', 'rb') as fp: data = pickle.load(fp)</code>
The above is the detailed content of How do you store Python dictionaries for later use?. For more information, please follow other related articles on the PHP Chinese website!