Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Python dictionaries

I'm used to bringing data in and out of Python using CSV files, but there are obvious challenges to this. Are there simple ways to store a dictionary (or sets of dictionaries) in a JSON or pickle file?

For example:

data = {} data ['key1'] = "keyinfo" data ['key2'] = "keyinfo2" 

I would like to know both how to save this, and then how to load it back in.

like image 457
mike Avatar asked Aug 17 '11 22:08

mike


People also ask

Can we save dictionary in Python?

Text Files The most basic way to save dictionaries in Python would be to store them as strings in text files. This method would include the following steps: Opening a file in write/append text mode. Converting the dictionary into a string.

Can Python dictionary store dictionaries?

A dictionary variable can store another dictionary in nested dictionary. The following example shows how nested dictionary can be declared and accessed using python. Here, 'courses' is a nested dictionary that contains other dictionary of three elements in each key.

Can I save dictionary to CSV Python?

In Python to convert a dictionary to CSV use the dictwriter() method. This method is used to insert data into the CSV file. In Python, the CSV module stores the dictwriter() method. It creates an object and works like the dictwriter().

How do I store a dictionary as a JSON file?

You can save the Python dictionary into JSON files using a built-in module json. We need to use json. dump() method to do this. Use the indent parameter to prettyPrint your JSON data.


2 Answers

Pickle save:

try:     import cPickle as pickle except ImportError:  # Python 3.x     import pickle  with open('data.p', 'wb') as fp:     pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL) 

See the pickle module documentation for additional information regarding the protocol argument.

Pickle load:

with open('data.p', 'rb') as fp:     data = pickle.load(fp) 

JSON save:

import json  with open('data.json', 'w') as fp:     json.dump(data, fp) 

Supply extra arguments, like sort_keys or indent, to get a pretty result. The argument sort_keys will sort the keys alphabetically and indent will indent your data structure with indent=N spaces.

json.dump(data, fp, sort_keys=True, indent=4) 

JSON load:

with open('data.json', 'r') as fp:     data = json.load(fp) 
like image 194
Marty Avatar answered Sep 23 '22 03:09

Marty


Minimal example, writing directly to a file:

import json json.dump(data, open(filename, 'wb')) data = json.load(open(filename)) 

or safely opening / closing:

import json with open(filename, 'wb') as outfile:     json.dump(data, outfile) with open(filename) as infile:     data = json.load(infile) 

If you want to save it in a string instead of a file:

import json json_str = json.dumps(data) data = json.loads(json_str) 
like image 36
agf Avatar answered Sep 21 '22 03:09

agf