How to store a Python dictionary as an Environment Variable
I don't know if this is what you were looking for, but I ended up here while trying to save a dictionary as a Linux environment variable to consume it on my app.
What I did was saving it as a string like this:
export BUILDING_ADMINS="{'+27792955555': 'De Wet','+27722855555': 'Marysol','+27878085555': 'Blomerus'}'
And then on your python code you read it and transform it into a dictionary using this (taken from: Convert a String representation of a Dictionary to a dictionary?):
import ast
import os
ba_dict = ast.literal_eval(os.environ["BUILDING_ADMINS"])
If you type
type(ba_dict)
You should see your string is now a dict.
<class 'dict'>
Hope this helps someone else!
An environment variable is not something a script user would like to set. Use the json
module and a file:
import json
with open('numbers') as f:
numbers = json.load(f)
print numbers['+27792955555'] # De Wet
When pushing to GitHub don't commit the numbers
file. Maybe commit an example one and add the real one to your .gitignore
.
If you choose to use the environment, you should serialize the Python dictionary as JSON and dump/load that when setting/getting the environment variable. You can access the environment using os
module's environ
attribute. You can dump/load JSON using the json
module. You might want to watch out for a maximum length on environment variables if there is such a thing.
If I were you I would use a sqlite database, see https://docs.python.org/2/library/sqlite3.html. This would give you persistence, a defined schema, and a nice interface for handling your data.