{"id":8122,"date":"2021-02-09T10:03:42","date_gmt":"2021-02-09T04:33:42","guid":{"rendered":"http:\/\/www.pythonpool.com\/?p=8122"},"modified":"2026-07-13T12:31:36","modified_gmt":"2026-07-13T07:01:36","slug":"python-shelve","status":"publish","type":"post","link":"https:\/\/www.pythonpool.com\/python-shelve\/","title":{"rendered":"Python shelve: Persistent Dictionary Storage and Safety"},"content":{"rendered":"<p><strong>Quick answer:<\/strong> shelve provides a persistent dictionary-like interface with string keys and pickle-serialized values. It is convenient for small local, single-user data, but dbm backend differences, concurrent writes, portability, and pickle trust limits make a real database the better choice for shared or transactional systems.<\/p>\n<figure class=\"pythonpool-article-visual\"><img src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-shelve.png\" alt=\"Python Pool infographic showing Python shelve string keys pickled values dbm file persistence sync and trusted data\" width=\"1536\" height=\"1024\" loading=\"lazy\" decoding=\"async\"><figcaption>shelve behaves like a persistent dictionary, but its dbm backend and pickle values make concurrency, portability, and trust boundaries important.<\/figcaption><\/figure>\n<p>Python <code>shelve<\/code> gives you a persistent dictionary for small local programs. It stores string keys and Python objects on disk, so a later run can open the same shelf and read the saved values back.<\/p>\n<p>The module is useful when plain text is too awkward and a full database would be extra work. A command-line tool, local cache, learning project, or one-user desktop script can often use a shelf for settings, counters, lightweight records, or computed results.<\/p>\n<p>A shelf is not a server database. It is backed by <code>dbm<\/code> and serializes values with <code>pickle<\/code>. That means it is simple and convenient, but it also inherits backend limits, platform differences, and the usual warning about loading pickled data only from trusted sources.<\/p>\n<p>The official Python documentation covers the <a href=\"https:\/\/docs.python.org\/3\/library\/shelve.html\">shelve module<\/a>, the underlying <a href=\"https:\/\/docs.python.org\/3\/library\/dbm.html\">dbm interfaces<\/a>, and the <a href=\"https:\/\/docs.python.org\/3\/library\/pickle.html\">pickle module<\/a>.<\/p>\n<p>Use <code>shelve<\/code> when the data naturally behaves like a mapping. Each key must be a string. Each value must be pickleable. If you need SQL queries, concurrent writers, transactions, remote access, or transparent data sharing across languages, choose SQLite, PostgreSQL, Redis, or another storage system instead.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-transparent ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #990303;color:#990303\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #990303;color:#990303\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 eztoc-toggle-hide-by-default' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#Create_A_Shelf\" >Create A Shelf<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#Choose_An_Open_Mode\" >Choose An Open Mode<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#Update_Mutable_Values\" >Update Mutable Values<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#Use_writeback_Carefully\" >Use writeback Carefully<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#Delete_Keys\" >Delete Keys<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#Clean_Up_Shelf_Files\" >Clean Up Shelf Files<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#Use_A_Context_Manager\" >Use A Context Manager<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#Understand_Writeback\" >Understand Writeback<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#Choose_The_Right_Storage\" >Choose The Right Storage<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#Treat_Values_As_Trusted\" >Treat Values As Trusted<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#Plan_For_Backend_Differences\" >Plan For Backend Differences<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#Frequently_Asked_Questions\" >Frequently Asked Questions<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#What_is_Python_shelve_used_for\" >What is Python shelve used for?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#Are_shelve_values_safe_to_load\" >Are shelve values safe to load?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#Can_multiple_processes_write_to_one_shelf\" >Can multiple processes write to one shelf?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/#What_type_must_shelve_keys_have\" >What type must shelve keys have?<\/a><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"Create_A_Shelf\"><\/span>Create A Shelf<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The basic flow is open, assign keys, close, then open again later. A context manager closes the shelf even if an error interrupts the block.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">import shelve\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\n\nwith TemporaryDirectory() as tmp:\n    shelf_path = str(Path(tmp) \/ \"students\")\n\n    with shelve.open(shelf_path) as shelf:\n        shelf[\"ada\"] = {\"course\": \"Python\", \"score\": 95}\n        shelf[\"grace\"] = {\"course\": \"Data tools\", \"score\": 91}\n\n    with shelve.open(shelf_path) as shelf:\n        print(sorted(shelf.keys()))\n        print(shelf[\"ada\"][\"score\"])\n<\/code><\/pre>\n<\/div>\n<p>This example writes two records and reads one back from a later shelf handle. The temporary directory keeps the sample from leaving backend files in the current folder.<\/p>\n<p>Depending on the platform, one shelf name can create one file or several related files. Treat the base name as the shelf path and let Python choose the backend details.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Choose_An_Open_Mode\"><\/span>Choose An Open Mode<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p><code>shelve.open()<\/code> accepts the same style of flag used by <code>dbm.open()<\/code>. The common choices are <code>\"c\"<\/code> to create if needed, <code>\"n\"<\/code> to start fresh, and <code>\"r\"<\/code> to read an existing shelf.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">import shelve\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\n\nwith TemporaryDirectory() as tmp:\n    shelf_path = str(Path(tmp) \/ \"settings\")\n\n    with shelve.open(shelf_path, flag=\"n\") as shelf:\n        shelf[\"theme\"] = \"dark\"\n        shelf[\"page_size\"] = 25\n\n    with shelve.open(shelf_path, flag=\"r\") as shelf:\n        print(shelf[\"theme\"])\n        print(shelf.get(\"missing\", \"fallback\"))\n<\/code><\/pre>\n<\/div>\n<p>Use <code>\"n\"<\/code> in examples and tests when you want a clean shelf every time. Use <code>\"c\"<\/code> in application code when an existing shelf should be reused or created if it does not exist yet.<\/p>\n<p>A read-only open is a good guard for reporting code. It communicates intent and avoids accidental updates while a script is only inspecting stored data.<\/p>\n<p><!-- Python Pool visual layout repair 2026-07-13 --><\/p>\n<figure class=\"pythonpool-article-visual pythonpool-supporting-visual\"><img src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/shelve-open-b210.png\" alt=\"Python Pool infographic showing a Python mapping, shelve.open, file-backed storage, and key\" width=\"1536\" height=\"1054\" loading=\"lazy\" decoding=\"async\"><figcaption>shelve provides a dictionary-like interface backed by a local database file.<\/figcaption><\/figure>\n<h2><span class=\"ez-toc-section\" id=\"Update_Mutable_Values\"><\/span>Update Mutable Values<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>A shelf stores serialized objects. If you read a list or dictionary, mutate it in memory, and do not write it back, the stored value may not change when <code>writeback<\/code> is false.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">import shelve\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\n\nwith TemporaryDirectory() as tmp:\n    shelf_path = str(Path(tmp) \/ \"orders\")\n\n    with shelve.open(shelf_path, flag=\"n\") as shelf:\n        shelf[\"cart\"] = {\"items\": [\"book\"], \"total\": 12}\n\n    with shelve.open(shelf_path, writeback=False) as shelf:\n        cart = shelf[\"cart\"]\n        cart[\"items\"].append(\"pen\")\n        cart[\"total\"] += 3\n        shelf[\"cart\"] = cart\n\n    with shelve.open(shelf_path) as shelf:\n        print(shelf[\"cart\"])\n<\/code><\/pre>\n<\/div>\n<p>The safest habit is to assign the changed object back to the key. That makes the write explicit and avoids relying on cache behavior that may surprise the next maintainer.<\/p>\n<p>This pattern also keeps memory use predictable. A shelf with many large objects should not keep everything cached just to catch nested updates.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Use_writeback_Carefully\"><\/span>Use writeback Carefully<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p><code>writeback=True<\/code> caches accessed entries and writes them back on sync or close. It can make nested edits convenient, but it may use more memory and can make closing slower if many entries were touched.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">import shelve\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\n\nwith TemporaryDirectory() as tmp:\n    shelf_path = str(Path(tmp) \/ \"preferences\")\n\n    with shelve.open(shelf_path, flag=\"n\", writeback=True) as shelf:\n        shelf[\"profile\"] = {\"name\": \"Ada\", \"history\": []}\n        profile = shelf[\"profile\"]\n        profile[\"history\"].append(\"opened\")\n        shelf.sync()\n\n    with shelve.open(shelf_path) as shelf:\n        print(shelf[\"profile\"][\"history\"])\n<\/code><\/pre>\n<\/div>\n<p>Use <code>writeback=True<\/code> only when the convenience is worth the cost. For small settings files it can be fine. For larger caches, explicit reassignment is usually clearer.<\/p>\n<p><code>sync()<\/code> asks the shelf to write pending changes to disk without closing it. It is still not a substitute for good error handling or for a storage engine with stronger durability rules.<\/p>\n<figure class=\"pythonpool-article-visual pythonpool-supporting-visual\"><img src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/shelve-write-b210.png\" alt=\"Python Pool infographic mapping a key and object through shelf assignment to persistent data\" width=\"1536\" height=\"1054\" loading=\"lazy\" decoding=\"async\"><figcaption>Values are serialized into shelf storage when written through the mapping interface.<\/figcaption><\/figure>\n<h2><span class=\"ez-toc-section\" id=\"Delete_Keys\"><\/span>Delete Keys<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>A shelf supports familiar mapping operations such as membership checks, deletion, iteration over keys, and length checks. These operations are helpful for maintenance commands and cleanup jobs.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">import shelve\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\n\nwith TemporaryDirectory() as tmp:\n    shelf_path = str(Path(tmp) \/ \"tasks\")\n\n    with shelve.open(shelf_path, flag=\"n\") as shelf:\n        shelf[\"active\"] = [\"write\", \"test\"]\n        shelf[\"draft\"] = \"remove this entry\"\n        print(\"draft\" in shelf)\n\n        del shelf[\"draft\"]\n        print(\"draft\" in shelf)\n        print(len(shelf))\n<\/code><\/pre>\n<\/div>\n<p>Deleting a key removes the stored entry, but it does not always shrink the backend files immediately. That detail depends on the selected <code>dbm<\/code> implementation.<\/p>\n<p>If a shelf grows and shrinks a lot, consider rebuilding it into a fresh shelf during a maintenance step or moving the data to a database designed for that workload.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Clean_Up_Shelf_Files\"><\/span>Clean Up Shelf Files<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>A shelf should be closed before moving, copying, backing up, or deleting its backend files. The context manager is the easiest way to make that reliable.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">import shelve\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\n\nwith TemporaryDirectory() as tmp:\n    folder = Path(tmp)\n    shelf_base = folder \/ \"inventory\"\n\n    with shelve.open(str(shelf_base), flag=\"n\") as shelf:\n        shelf[\"count\"] = 3\n\n    created = sorted(path.name for path in folder.glob(\"inventory*\"))\n    print(created)\n\nprint(Path(tmp).exists())\n<\/code><\/pre>\n<\/div>\n<p>The final print is <code>False<\/code> because the temporary directory has been removed. In a real project, choose an application data directory deliberately and keep the shelf files together.<\/p>\n<p>Do not unpickle shelves from people or systems you do not trust. Because <code>shelve<\/code> uses <code>pickle<\/code>, opening hostile data can run code during loading. For shared or user-supplied data, use JSON, CSV, SQLite, or another safer format.<\/p>\n<p>In short, <code>shelve<\/code> is best for trusted, local, dictionary-shaped persistence. Keep keys as strings, write mutable values back explicitly, use read-only mode for inspection, close shelves with context managers, and move to a stronger database when the data needs concurrency or query features.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Use_A_Context_Manager\"><\/span>Use A Context Manager<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Open a shelf with a context manager so it closes even when an exception interrupts the operation. Assign string keys and pickleable values, then reopen the shelf to read persisted state.<\/p>\n<figure class=\"pythonpool-article-visual pythonpool-supporting-visual\"><img src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/shelve-sync-b210.png\" alt=\"Python Pool infographic comparing shelf mutation, sync, close, and durable file state\" width=\"1536\" height=\"1054\" loading=\"lazy\" decoding=\"async\"><figcaption>Close the shelf and use sync deliberately when durability timing matters.<\/figcaption><\/figure>\n<h2><span class=\"ez-toc-section\" id=\"Understand_Writeback\"><\/span>Understand Writeback<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Mutable values retrieved from a shelf are not automatically persisted after in-place mutation unless writeback behavior or an explicit reassignment is used. Reassign updated values when predictable persistence matters.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Choose_The_Right_Storage\"><\/span>Choose The Right Storage<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>shelve fits small local settings, caches, and learning projects. SQLite or a server database is more appropriate for queries, transactions, multiple writers, remote access, or cross-language data.<\/p>\n<figure class=\"pythonpool-article-visual pythonpool-supporting-visual\"><img src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/shelve-check-b210.png\" alt=\"Python Pool infographic testing trust, locking, portability, corruption, and validation\" width=\"1536\" height=\"1054\" loading=\"lazy\" decoding=\"async\"><figcaption>Never load untrusted shelf data; check locking, portability, corruption, and concurrent access.<\/figcaption><\/figure>\n<h2><span class=\"ez-toc-section\" id=\"Treat_Values_As_Trusted\"><\/span>Treat Values As Trusted<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>shelve uses pickle for values, so opening an untrusted shelf can execute code. Protect the file and choose a safer interchange format when its source is not fully trusted.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Plan_For_Backend_Differences\"><\/span>Plan For Backend Differences<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The underlying dbm implementation and file behavior can vary across operating systems. Test backup, migration, locking, corruption recovery, and deployment on the actual target platform.<\/p>\n<p>The <a href=\"https:\/\/docs.python.org\/3\/library\/shelve.html\">Python shelve documentation<\/a> covers keys, values, writeback, and security. Related references include <a href=\"https:\/\/www.pythonpool.com\/cpickle\/\">pickle migration<\/a>, <a href=\"https:\/\/www.pythonpool.com\/fixed-valueerror-unsupported-pickle-protocol-5\/\">protocol compatibility<\/a>, and <a href=\"https:\/\/www.pythonpool.com\/python-testing-framework\/\">persistence tests<\/a>.<\/p>\n<p>For related persistence choices, compare <a href=\"https:\/\/www.pythonpool.com\/cpickle\/\">pickle migration<\/a>, <a href=\"https:\/\/www.pythonpool.com\/fixed-valueerror-unsupported-pickle-protocol-5\/\">protocol compatibility<\/a>, and <a href=\"https:\/\/www.pythonpool.com\/python-testing-framework\/\">persistence tests<\/a> when storing local state.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Frequently_Asked_Questions\"><\/span>Frequently Asked Questions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"What_is_Python_shelve_used_for\"><\/span>What is Python shelve used for?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>It stores string-keyed Python objects persistently for small local programs, caches, settings, and lightweight single-user data.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Are_shelve_values_safe_to_load\"><\/span>Are shelve values safe to load?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Only load shelves from a trusted source because values are serialized with pickle.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Can_multiple_processes_write_to_one_shelf\"><\/span>Can multiple processes write to one shelf?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Concurrent read and write access is not a safe default; use a real database when transactions or multiple writers matter.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"What_type_must_shelve_keys_have\"><\/span>What type must shelve keys have?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Keys must be strings, while values must be pickleable objects.<\/p>\n<p><script type=\"application\/ld+json\">{\"@context\":\"https:\/\/schema.org\",\"@type\":\"FAQPage\",\"mainEntity\":[{\"@type\":\"Question\",\"name\":\"What is Python shelve used for?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"It stores string-keyed Python objects persistently for small local programs, caches, settings, and lightweight single-user data.\"}},{\"@type\":\"Question\",\"name\":\"Are shelve values safe to load?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Only load shelves from a trusted source because values are serialized with pickle.\"}},{\"@type\":\"Question\",\"name\":\"Can multiple processes write to one shelf?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Concurrent read and write access is not a safe default; use a real database when transactions or multiple writers matter.\"}},{\"@type\":\"Question\",\"name\":\"What type must shelve keys have?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Keys must be strings, while values must be pickleable objects.\"}}]}<\/script><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Use Python shelve for small persistent mappings, choose modes, manage sync and keys, and understand dbm, pickle, concurrency, and trust limits.<\/p>\n","protected":false},"author":12,"featured_media":34100,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_mi_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[15],"tags":[3504,3505,3503,3502,3501],"class_list":["post-8122","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tutorials","tag-python-shelve-example","tag-python-shelve-module","tag-python-shelve-query","tag-python-shelve-tutorial","tag-shelve-python","infinite-scroll-item"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v20.1 (Yoast SEO v28.0) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Python shelve: Persistent Dictionary Storage and Safety<\/title>\n<meta name=\"description\" content=\"Use Python shelve for small persistent mappings, choose modes, manage sync and keys, and understand dbm, pickle, concurrency, and trust limits.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.pythonpool.com\/python-shelve\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python shelve: Persistent Dictionary Storage and Safety\" \/>\n<meta property=\"og:description\" content=\"Use Python shelve for small persistent mappings, choose modes, manage sync and keys, and understand dbm, pickle, concurrency, and trust limits.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pythonpool.com\/python-shelve\/\" \/>\n<meta property=\"og:site_name\" content=\"Python Pool\" \/>\n<meta property=\"article:published_time\" content=\"2021-02-09T04:33:42+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-07-13T07:01:36+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-shelve.png\" \/>\n<meta name=\"author\" content=\"Prachee Sao\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:title\" content=\"Python Pool\" \/>\n<meta name=\"twitter:description\" content=\"Practical Python tutorials, error fixes, code examples, and project guides.\" \/>\n<meta name=\"twitter:image\" content=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-shelve.png\" \/>\n<meta name=\"twitter:creator\" content=\"@pythonpool\" \/>\n<meta name=\"twitter:site\" content=\"@pythonpool\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Prachee Sao\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-shelve\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-shelve\\\/\"},\"author\":{\"name\":\"Prachee Sao\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#\\\/schema\\\/person\\\/b91d749826b21e606d55cda77d51ef47\"},\"headline\":\"Python shelve: Persistent Dictionary Storage and Safety\",\"datePublished\":\"2021-02-09T04:33:42+00:00\",\"dateModified\":\"2026-07-13T07:01:36+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-shelve\\\/\"},\"wordCount\":1147,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-shelve\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2026\\\/07\\\/python-shelve-persistent-dictionary-guide-pythonpool.png\",\"keywords\":[\"python shelve example\",\"python shelve module\",\"python shelve query\",\"python shelve tutorial\",\"shelve python\"],\"articleSection\":[\"Tutorials\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.pythonpool.com\\\/python-shelve\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-shelve\\\/\",\"url\":\"https:\\\/\\\/www.pythonpool.com\\\/python-shelve\\\/\",\"name\":\"Python shelve: Persistent Dictionary Storage and Safety\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-shelve\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-shelve\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2026\\\/07\\\/python-shelve-persistent-dictionary-guide-pythonpool.png\",\"datePublished\":\"2021-02-09T04:33:42+00:00\",\"dateModified\":\"2026-07-13T07:01:36+00:00\",\"description\":\"Use Python shelve for small persistent mappings, choose modes, manage sync and keys, and understand dbm, pickle, concurrency, and trust limits.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-shelve\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.pythonpool.com\\\/python-shelve\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-shelve\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2026\\\/07\\\/python-shelve-persistent-dictionary-guide-pythonpool.png\",\"contentUrl\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2026\\\/07\\\/python-shelve-persistent-dictionary-guide-pythonpool.png\",\"width\":1350,\"height\":650,\"caption\":\"Python shelve persistent dictionary guide\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-shelve\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.pythonpool.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python shelve: Persistent Dictionary Storage and Safety\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#website\",\"url\":\"https:\\\/\\\/www.pythonpool.com\\\/\",\"name\":\"Python Pool\",\"description\":\"Practical Python tutorials, error fixes, code examples, and project guides.\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.pythonpool.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#organization\",\"name\":\"Python Pool\",\"url\":\"https:\\\/\\\/www.pythonpool.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2020\\\/08\\\/aa.png\",\"contentUrl\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2020\\\/08\\\/aa.png\",\"width\":452,\"height\":185,\"caption\":\"Python Pool\"},\"image\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/x.com\\\/pythonpool\",\"https:\\\/\\\/www.youtube.com\\\/c\\\/pythonpool\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#\\\/schema\\\/person\\\/b91d749826b21e606d55cda77d51ef47\",\"name\":\"Prachee Sao\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/d018c3758049ab2511d0772ac1f73c338aaa8c921577f39e0f1e5716fc7efcb4?s=96&d=wavatar&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/d018c3758049ab2511d0772ac1f73c338aaa8c921577f39e0f1e5716fc7efcb4?s=96&d=wavatar&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/d018c3758049ab2511d0772ac1f73c338aaa8c921577f39e0f1e5716fc7efcb4?s=96&d=wavatar&r=g\",\"caption\":\"Prachee Sao\"}}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Python shelve: Persistent Dictionary Storage and Safety","description":"Use Python shelve for small persistent mappings, choose modes, manage sync and keys, and understand dbm, pickle, concurrency, and trust limits.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.pythonpool.com\/python-shelve\/","og_locale":"en_US","og_type":"article","og_title":"Python shelve: Persistent Dictionary Storage and Safety","og_description":"Use Python shelve for small persistent mappings, choose modes, manage sync and keys, and understand dbm, pickle, concurrency, and trust limits.","og_url":"https:\/\/www.pythonpool.com\/python-shelve\/","og_site_name":"Python Pool","article_published_time":"2021-02-09T04:33:42+00:00","article_modified_time":"2026-07-13T07:01:36+00:00","og_image":[{"url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-shelve.png","type":"","width":"","height":""}],"author":"Prachee Sao","twitter_card":"summary_large_image","twitter_title":"Python Pool","twitter_description":"Practical Python tutorials, error fixes, code examples, and project guides.","twitter_image":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-shelve.png","twitter_creator":"@pythonpool","twitter_site":"@pythonpool","twitter_misc":{"Written by":"Prachee Sao","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.pythonpool.com\/python-shelve\/#article","isPartOf":{"@id":"https:\/\/www.pythonpool.com\/python-shelve\/"},"author":{"name":"Prachee Sao","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/b91d749826b21e606d55cda77d51ef47"},"headline":"Python shelve: Persistent Dictionary Storage and Safety","datePublished":"2021-02-09T04:33:42+00:00","dateModified":"2026-07-13T07:01:36+00:00","mainEntityOfPage":{"@id":"https:\/\/www.pythonpool.com\/python-shelve\/"},"wordCount":1147,"commentCount":0,"publisher":{"@id":"https:\/\/www.pythonpool.com\/#organization"},"image":{"@id":"https:\/\/www.pythonpool.com\/python-shelve\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-shelve-persistent-dictionary-guide-pythonpool.png","keywords":["python shelve example","python shelve module","python shelve query","python shelve tutorial","shelve python"],"articleSection":["Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.pythonpool.com\/python-shelve\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.pythonpool.com\/python-shelve\/","url":"https:\/\/www.pythonpool.com\/python-shelve\/","name":"Python shelve: Persistent Dictionary Storage and Safety","isPartOf":{"@id":"https:\/\/www.pythonpool.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.pythonpool.com\/python-shelve\/#primaryimage"},"image":{"@id":"https:\/\/www.pythonpool.com\/python-shelve\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-shelve-persistent-dictionary-guide-pythonpool.png","datePublished":"2021-02-09T04:33:42+00:00","dateModified":"2026-07-13T07:01:36+00:00","description":"Use Python shelve for small persistent mappings, choose modes, manage sync and keys, and understand dbm, pickle, concurrency, and trust limits.","breadcrumb":{"@id":"https:\/\/www.pythonpool.com\/python-shelve\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pythonpool.com\/python-shelve\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/python-shelve\/#primaryimage","url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-shelve-persistent-dictionary-guide-pythonpool.png","contentUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-shelve-persistent-dictionary-guide-pythonpool.png","width":1350,"height":650,"caption":"Python shelve persistent dictionary guide"},{"@type":"BreadcrumbList","@id":"https:\/\/www.pythonpool.com\/python-shelve\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.pythonpool.com\/"},{"@type":"ListItem","position":2,"name":"Python shelve: Persistent Dictionary Storage and Safety"}]},{"@type":"WebSite","@id":"https:\/\/www.pythonpool.com\/#website","url":"https:\/\/www.pythonpool.com\/","name":"Python Pool","description":"Practical Python tutorials, error fixes, code examples, and project guides.","publisher":{"@id":"https:\/\/www.pythonpool.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.pythonpool.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.pythonpool.com\/#organization","name":"Python Pool","url":"https:\/\/www.pythonpool.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png","contentUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png","width":452,"height":185,"caption":"Python Pool"},"image":{"@id":"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/pythonpool","https:\/\/www.youtube.com\/c\/pythonpool"]},{"@type":"Person","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/b91d749826b21e606d55cda77d51ef47","name":"Prachee Sao","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/d018c3758049ab2511d0772ac1f73c338aaa8c921577f39e0f1e5716fc7efcb4?s=96&d=wavatar&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/d018c3758049ab2511d0772ac1f73c338aaa8c921577f39e0f1e5716fc7efcb4?s=96&d=wavatar&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/d018c3758049ab2511d0772ac1f73c338aaa8c921577f39e0f1e5716fc7efcb4?s=96&d=wavatar&r=g","caption":"Prachee Sao"}}]}},"_links":{"self":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/8122","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/users\/12"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/comments?post=8122"}],"version-history":[{"count":17,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/8122\/revisions"}],"predecessor-version":[{"id":41560,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/8122\/revisions\/41560"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/media\/34100"}],"wp:attachment":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/media?parent=8122"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/categories?post=8122"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/tags?post=8122"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}