A dictionary with NumPy arrays as tuple values! That's a interesting data structure. Saving it efficiently requires a format that can handle both the dictionary structure and the NumPy arrays. Here are a few options, each with their pros and cons:
You can use NumPy's built-in savez() or savez_compressed() functions to save the dictionary. These functions store multiple arrays in a single file with a .npz extension, which is a ZIP archive containing .npy files (one per array).
Here's how to do it:
python
import numpy as np
# your dictionary with tuple values
dict_with_arrays = {
'key1': (np.array([1, 2, 3]), np.array([4, 5, 6])),
'key2': (np.array([7, 8, 9]), np.array([10, 11, 12]))
}
# flatten the dictionary values into a list of arrays
arrays = []
keys = []
for key, value in dict_with_arrays.items():
for i, arr in enumerate(value):
arrays.append(arr)
keys.append(f"{key}_{i}") # e.g., "key1_0", "key1_1", ...
# save the arrays
np.savez_compressed("data.npz", **{k: v for k, v in zip(keys, arrays)})
To load the data:
python
loaded = np.load("data.npz")
reconstructed_dict = {}
for key in loaded.files:
orig_key, idx = key.rsplit("_", 1)
idx = int(idx)
if orig_key not in reconstructed_dict:
reconstructed_dict[orig_key] = (loaded[key],)
else:
reconstructed_dict[orig_key] += (loaded[key],)
print(reconstructed_dict)
Pros: Fast, efficient compression (with savez_compressed()), and easy to use.
Cons: You'll need to reconstruct the original dictionary structure when loading, as .npz files don't store dictionary keys directly.
2. Pickle (.pkl file)
Python's pickle module can serialize almost any Python object, including your dictionary with NumPy arrays.
python
import pickle
# save
with open("data.pkl", "wb") as f:
pickle.dump(dict_with_arrays, f)
# load
with open("data.pkl", "rb") as f:
loaded_dict = pickle.load(f)
Pros: Extremely easy to use, preserves the dictionary structure.
Cons: Not secure against erroneous or maliciously constructed data (don't unpickle data from unknown sources!). Also, Pickle files can be slower and larger than .npz files.
3. HDF5 (.h5 file) via h5py
HDF5 is a data storage format designed for large numerical datasets. h5py is a Pythonic interface to HDF5.
python
import h5py
# save
with h5py.File("data.h5", "w") as f:
for key, value in dict_with_arrays.items():
grp = f.create_group(key)
for i, arr in enumerate(value):
grp.create_dataset(f"arr_{i}", data=arr)
# load
with h5py.File("data.h5", "r") as f:
loaded_dict = {}
for key in f.keys():
grp = f[key]
loaded_dict[key] = tuple(grp[f"arr_{i}"][:] for i in range(len(grp)))
Pros: Efficient storage, fast read/write, supports large datasets, and has good compression options.
Cons: Requires an extra library (h5py), slightly more verbose than the other options.
4. JSON + Base64 (.json file)
If you need a human-readable format, you can convert NumPy arrays to Base64-encoded strings and store them in a JSON file.
python
import json
import base64
# helper function to convert array to Base64 string
def array_to_b64(arr):
return base64.b64encode(arr.tobytes()).decode("utf-8")
# save
dict_b64 = {k: [array_to_b64(arr) for arr in v] for k, v in dict_with_arrays.items()}
with open("data.json", "w") as f:
json.dump(dict_b64, f)
# load ( inverse of array_to_b64() )
def b64_to_array(b64_str, dtype=np.float64):
return np.frombuffer(base64.b64decode(b64_str), dtype=dtype)
with open("data.json", "r") as f:
loaded_dict_b64 = json.load(f)
loaded_dict = {k: tuple(b64_to_array(s) for s in v) for k, v in loaded_dict_b64.items()}