{ "cells": [ { "cell_type": "markdown", "id": "c452598e", "metadata": {}, "source": [ "# Pickle examples" ] }, { "cell_type": "markdown", "id": "a1406ad8", "metadata": {}, "source": [ "## Python `pickle` module\n", "\n", "In this example we want to use the Python [pickle](https://docs.python.org/3/library/pickle.html) module to save the following dict in pickle format:" ] }, { "cell_type": "code", "execution_count": 1, "id": "db7ff3f7", "metadata": {}, "outputs": [], "source": [ "pyviz = {\n", " \"Title\": \"PyViz Tutorial\",\n", " \"Language\": \"de\",\n", " \"Authors\": \"Veit Schiele\",\n", " \"License\": \"BSD-3-Clause\",\n", " \"Publication date\": \"2020-04-13\",\n", "}" ] }, { "cell_type": "code", "execution_count": 2, "id": "a247fb7a", "metadata": {}, "outputs": [], "source": [ "import pickle" ] }, { "cell_type": "code", "execution_count": 3, "id": "c842fe04", "metadata": {}, "outputs": [], "source": [ "with open(\"pyviz.pkl\", \"wb\") as f:\n", " pickle.dump(pyviz, f, pickle.HIGHEST_PROTOCOL)" ] }, { "cell_type": "markdown", "id": "b8b2a92f", "metadata": {}, "source": [ "Now we read the pickle file again:" ] }, { "cell_type": "code", "execution_count": 4, "id": "25d7b260", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'Title': 'PyViz Tutorial', 'Language': 'de', 'Authors': 'Veit Schiele', 'License': 'BSD-3-Clause', 'Publication date': '2020-04-13'}\n" ] } ], "source": [ "with open(\"pyviz.pkl\", \"rb\") as f:\n", " pyviz = pickle.load(f)\n", "\n", "print(pyviz)" ] }, { "cell_type": "markdown", "id": "0590401c", "metadata": {}, "source": [ "This way we can easily store Python objects persistently.\n", "\n", "
| \n", " | id | \n", "title | \n", "language | \n", "author | \n", "license | \n", "date | \n", "
|---|---|---|---|---|---|---|
| 0 | \n", "1 | \n", "Python basics | \n", "en | \n", "Veit Schiele | \n", "BSD-3-Clause | \n", "2021-10-28 | \n", "
| 1 | \n", "2 | \n", "Jupyter Tutorial | \n", "en | \n", "Veit Schiele | \n", "BSD-3-Clause | \n", "2019-06-27 | \n", "
| 2 | \n", "3 | \n", "Jupyter Tutorial | \n", "de | \n", "Veit Schiele | \n", "BSD-3-Clause | \n", "2020-10-26 | \n", "
| 3 | \n", "4 | \n", "PyViz Tutorial | \n", "en | \n", "Veit Schiele | \n", "BSD-3-Clause | \n", "2020-04-13 | \n", "