Save/Load a Dictionary

2024/4/15 0:34:55

I've found a couple of others asking for help with this, but not specifically what I'm trying to do. I have a dictionary full of various formats (int, str, bool, etc) and I'm trying to save it so I can load it at a later time. Here is a basic version of the code without all the extra trappings that are irrelevant for this.

petStats = { 'name':"", 'int':1, 'bool':False }def petSave(pet):with open(pet['name']+".txt", "w+") as file:for k,v in pet.items():file.write(str(k) + ':' + str(v) + "\n")def digimonLoad(petName):dStat = {}with open(petName+".txt", "r") as file:for line in file:(key, val) = line.split(":")dStat[str(key)] = valprint(petName,"found. Loading",petName+".")return dStat

In short I'm just brute forcing it by saving a text file with a Key:Value on each line, then split them all back up on load. Unfortunately this turns all of my int and bool into strings. Is there a file format I could use to save a dictionary to (I don't need to be able to read it, but the conveniance would be nice) that I could easily load back in?

This works for a basic dictionary but if I start adding things like arrays this is going to get out of hand as it is.


Use pickle. This is part of the standard library, so you can just import it.

import picklepet_stats = {'name':"", 'int':1, 'bool':False}def pet_save(pet):with open(pet['name'] + '.pickle', 'wb') as f:pickle.dump(pet, f, pickle.HIGHEST_PROTOCOL)def digimon_load(pet_name):with open(pet_name + '.pickle', 'rb') as f:return pickle.load(f)

Pickle works on more data types than JSON, and automatically loads them as the right Python type. (There are ways to save more types with JSON, but it takes more work.) JSON (or XML) is better if you need the output to be human-readable, or need to share it with non-Python programs, but neither appears to be necessary for your use case. Pickle will be easiest.

If you need to see what's in the file, just load it using Python or

python -m pickle foo.pickle

instead of a text editor. (Only do this to pickle files from sources you trust, pickle is not at all secure against hacking.)

Related Q&A

py2exe error handling redirection and popup

Been trying to figure out how to get py2exe to handle errors more gracefully. There are basically 2 weird things happening:1) Popup message after shutting down the program => want to suppress (not …

SQL statement for CSV files on IPython notebook

I have a tabledata.csv file and I have been using pandas.read_csv to read or choose specific columns with specific conditions.For instance I use the following code to select all "name" where …

How to draw ellipsoid with plotly

Are there any way to plot a surface like ellipsoid with plotly 3D?Currently only surfaces of the form z=f(x,y) are discussed in the docs. There is also Mesh 3D, but I found no examples for it. It seem…

PyTorch DataLoader uses same random seed for batches run in parallel

There is a bug in PyTorch/Numpy where when loading batches in parallel with a DataLoader (i.e. setting num_workers > 1), the same NumPy random seed is used for each worker, resulting in any random f…

How to fix 502 Bad Gateway Error in production(Nginx)?

When I tried to upload a big csv file of size about 600MB in my project which is hosted in the digital ocean, it tries to upload but shows 502 Bad Gateway Error (Nginx). The application is a data conve…

Shift theorem in Discrete Fourier Transform

Im trying to solve a problem with python+numpy in which Ive some functions of type that I need to convolve with another function . In order to optimize code, I performed the fft of f and g, I multipli…

Running pudb inside docker container

I prefer pudb for python debugging. I am building python applications that run inside docker container. Does any one know how to make pudb available inside docker container?Thank you

Argparse: defaults from file

I have a Python script which takes a lot of arguments. I currently use a configuration.ini file (read using configparser), but would like to allow the user to override specific arguments using command …

How can access Uploaded File in Google colab

Im new in python and I use Google Colab . I uploaded a train_data.npy into google Colab and then I want to use it . According to this link How to import and read a shelve or Numpy file in Google Colabo…

__add__ to support addition of different types?

Would be very easy to solve had python been a static programming language that supported overloading. I am making a class called Complex which is a representation of complex numbers (I know python has …