Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to store dictionary permanently with Python?

Tags:

Currently expensively parsing a file, which generates a dictionary of ~400 key, value pairs, which is seldomly updated. Previously had a function which parsed the file, wrote it to a text file in dictionary syntax (ie. dict = {'Adam': 'Room 430', 'Bob': 'Room 404'}) etc, and copied and pasted it into another function whose sole purpose was to return that parsed dictionary.

Hence, in every file where I would use that dictionary, I would import that function, and assign it to a variable, which is now that dictionary. Wondering if there's a more elegant way to do this, which does not involve explicitly copying and pasting code around? Using a database kind of seems unnecessary, and the text file gave me the benefit of seeing whether the parsing was done correctly before adding it to the function. But I'm open to suggestions.

like image 552
zhuyxn Avatar asked Aug 06 '12 00:08

zhuyxn


People also ask

What is the best way to save a Python dictionary?

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.

How do I save a large dictionary in Python?

If you just want to work with a larger dictionary than memory can hold, the shelve module is a good quick-and-dirty solution. It acts like an in-memory dict, but stores itself on disk rather than in memory. shelve is based on cPickle, so be sure to set your protocol to anything other than 0.

Can you store a dictionary in a dictionary Python?

In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary. Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB . They are two dictionary each having own key and value.

How do I store a dictionary in JSON?

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.


1 Answers

Why not dump it to a JSON file, and then load it from there where you need it?

import json  with open('my_dict.json', 'w') as f:     json.dump(my_dict, f)  # elsewhere...  with open('my_dict.json') as f:     my_dict = json.load(f) 

Loading from JSON is fairly efficient.

Another option would be to use pickle, but unlike JSON, the files it generates aren't human-readable so you lose out on the visual verification you liked from your old method.

like image 137
Amber Avatar answered Sep 19 '22 16:09

Amber