{"id":23434,"date":"2022-11-13T21:04:35","date_gmt":"2022-11-13T15:34:35","guid":{"rendered":"http:\/\/www.pythonpool.com\/?p=23434"},"modified":"2026-07-13T12:40:27","modified_gmt":"2026-07-13T07:10:27","slug":"python-sorteddict","status":"publish","type":"post","link":"https:\/\/www.pythonpool.com\/python-sorteddict\/","title":{"rendered":"Python SortedDict: Sorted Containers, Keys, and Updates"},"content":{"rendered":"<p><strong>Quick answer:<\/strong> SortedDict from sortedcontainers is a mapping that maintains keys in sorted order and supports ordered access. Use it when you need recurring sorted-key operations or range-style navigation; use the built-in dict when insertion order and ordinary key lookup are enough.<\/p>\n<figure class=\"pythonpool-article-visual\"><img src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-sorteddict.png\" alt=\"Python Pool infographic comparing dict and SortedDict insertion, sorted keys, lookup, updates, and range access\" width=\"1536\" height=\"1024\" loading=\"lazy\" decoding=\"async\"><figcaption>SortedDict maintains keys in sorted order through a sortedcontainers data structure; choose it when ordered mapping operations matter more than a built-in dict alone.<\/figcaption><\/figure>\n<p><code>SortedDict<\/code> is a sorted mapping from the third-party <code>sortedcontainers<\/code> package. It behaves like a dictionary, but it keeps keys in sorted order. That makes it useful when you need dictionary-style lookup plus predictable key order, range-style key access, or sorted iteration without sorting keys every time.<\/p>\n<p><code>SortedDict<\/code> is not part of the Python standard library. Install <code>sortedcontainers<\/code> in your environment and import <code>SortedDict<\/code> with the exact capitalization. The <a href=\"https:\/\/grantjenks.com\/docs\/sortedcontainers\/sorteddict.html\">SortedDict documentation<\/a> covers the API, and the <a href=\"https:\/\/pypi.org\/project\/sortedcontainers\/\">sortedcontainers PyPI page<\/a> covers package installation details.<\/p>\n<p>Use a normal <code>dict<\/code> when insertion order is enough or when you only need fast key lookup. Use <code>SortedDict<\/code> when sorted key order is part of the operation. For standard sorting patterns, see the <a href=\"https:\/\/www.pythonpool.com\/sort-dictionary-by-key-in-python\/\">sort dictionary by key<\/a> guide.<\/p>\n<p>The key difference is where the sorting cost lives. With a plain dictionary, you often sort keys at the moment you need sorted output. With <code>SortedDict<\/code>, the container maintains sorted key order as items are inserted, updated, or removed. That can make code easier to read when sorted traversal happens many times in the same workflow.<\/p>\n<p>This is especially helpful for lookup tables keyed by numbers, timestamps, names, priorities, or any other comparable key where the next, previous, smallest, or largest key matters. It can also be useful in reporting code, scheduling logic, leaderboard-like views, and tools that need stable sorted output after every update.<\/p>\n<p>Before choosing it, check whether the sorted order is truly part of the data structure you need. If the program only prints a sorted report once, a plain dictionary plus <code>sorted()<\/code> is usually enough. If the program repeatedly asks for sorted keys, indexed positions, or nearby keys, <code>SortedDict<\/code> gives those operations a clearer home.<\/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-sorteddict\/#Create_A_SortedDict\" >Create A SortedDict<\/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-sorteddict\/#Add_Update_And_Delete_Items\" >Add, Update, And Delete Items<\/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-sorteddict\/#Iterate_In_Sorted_Key_Order\" >Iterate In Sorted Key Order<\/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-sorteddict\/#Find_Key_Positions_With_Bisect\" >Find Key Positions With Bisect<\/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-sorteddict\/#Read_Keys_In_Reverse_Order\" >Read Keys In Reverse Order<\/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-sorteddict\/#Sort_By_Value_Separately\" >Sort By Value Separately<\/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-sorteddict\/#Install_And_Create_SortedDict\" >Install And Create SortedDict<\/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-sorteddict\/#Add_Update_And_Delete_Keys\" >Add, Update, And Delete Keys<\/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-sorteddict\/#Use_Ordered_Navigation\" >Use Ordered Navigation<\/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-sorteddict\/#Compare_With_A_Built-In_dict\" >Compare With A Built-In dict<\/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-sorteddict\/#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-12\" href=\"https:\/\/www.pythonpool.com\/python-sorteddict\/#What_is_SortedDict_in_Python\" >What is SortedDict in Python?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.pythonpool.com\/python-sorteddict\/#How_is_SortedDict_different_from_dict\" >How is SortedDict different from dict?<\/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-sorteddict\/#How_do_I_install_SortedDict\" >How do I install SortedDict?<\/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-sorteddict\/#When_should_I_use_SortedDict\" >When should I use SortedDict?<\/a><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"Create_A_SortedDict\"><\/span>Create A SortedDict<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Create a <code>SortedDict<\/code> from key-value pairs just like a normal dictionary. Iteration follows sorted key order.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">from sortedcontainers import SortedDict\n\nscores = SortedDict({\"maya\": 92, \"noah\": 85, \"iris\": 97})\n\nprint(list(scores.keys()))\nprint(scores[\"iris\"])\n<\/code><\/pre>\n<\/div>\n<p>The keys are sorted according to their normal comparison behavior. Keep key types consistent; mixing unrelated key types can raise comparison errors in modern Python.<\/p>\n<p>String keys sort lexicographically, while numeric keys sort by numeric order. Custom objects can be used only when Python knows how to compare them. In most practical code, simple strings, integers, dates, or tuples make the behavior predictable and easy to test.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Add_Update_And_Delete_Items\"><\/span>Add, Update, And Delete Items<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Assignment works the same way as it does with <code>dict<\/code>. New keys are inserted into the sorted key order, and existing keys are updated.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">from sortedcontainers import SortedDict\n\nscores = SortedDict({\"maya\": 92, \"noah\": 85})\nscores[\"iris\"] = 97\nscores[\"noah\"] = 88\ndel scores[\"maya\"]\n\nprint(scores)\n<\/code><\/pre>\n<\/div>\n<p>Use <code>del<\/code> when the key must exist. Use <code>pop()<\/code> when you want to remove a key and keep the removed value.<\/p>\n<p>Membership checks also work the same way as a dictionary. You can use <code>in<\/code> to check whether a key exists, <code>get()<\/code> to read with a fallback, and <code>setdefault()<\/code> when you want to create a default entry only if the key is missing. The difference is that the key order remains sorted after each change.<\/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\/sorteddict-mapping-b211.png\" alt=\"Python Pool infographic showing keys, values, sorted order, and SortedDict mapping\" width=\"1536\" height=\"1054\" loading=\"lazy\" decoding=\"async\"><figcaption>SortedDict maintains a mapping whose keys are kept in sorted order.<\/figcaption><\/figure>\n<h2><span class=\"ez-toc-section\" id=\"Iterate_In_Sorted_Key_Order\"><\/span>Iterate In Sorted Key Order<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The main benefit is that keys, values, and items follow sorted key order during iteration.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">from sortedcontainers import SortedDict\n\ninventory = SortedDict({30: \"monitor\", 10: \"keyboard\", 20: \"mouse\"})\n\nfor item_id, name in inventory.items():\n    print(item_id, name)\n<\/code><\/pre>\n<\/div>\n<p>This avoids repeatedly calling <code>sorted(my_dict)<\/code> when sorted traversal is a normal part of the program.<\/p>\n<p>That sorted traversal can make output more dependable. Tests become easier to compare, command-line reports are easier to scan, and serialized data can remain stable between runs. Stable order is also helpful when a later step depends on processing lower keys before higher keys.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Find_Key_Positions_With_Bisect\"><\/span>Find Key Positions With Bisect<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p><code>SortedDict<\/code> exposes bisect-style helpers for finding where a key would appear. This is useful for range queries and nearest-key logic.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">from sortedcontainers import SortedDict\n\nprices = SortedDict({10: \"low\", 20: \"medium\", 30: \"high\"})\n\nprint(prices.bisect_key_left(20))\nprint(prices.bisect_key_right(20))\nprint(prices.peekitem(0))\n<\/code><\/pre>\n<\/div>\n<p><code>bisect_key_left()<\/code> and <code>bisect_key_right()<\/code> return insertion indexes. <code>peekitem()<\/code> returns a key-value pair by sorted index.<\/p>\n<p>These helpers are the main reason to choose <code>SortedDict<\/code> over sorting a dictionary view on demand. They let you reason about key positions directly, without building a separate sorted list every time. For larger collections or repeated checks, that keeps the surrounding code smaller and more direct.<\/p>\n<figure class=\"pythonpool-article-visual pythonpool-supporting-visual\"><img src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/sorteddict-range-b211.png\" alt=\"Python Pool infographic comparing SortedDict keys, irange, range bounds, and selected values\" width=\"1536\" height=\"1054\" loading=\"lazy\" decoding=\"async\"><figcaption>Sorted mappings can expose efficient range-oriented key iteration.<\/figcaption><\/figure>\n<h2><span class=\"ez-toc-section\" id=\"Read_Keys_In_Reverse_Order\"><\/span>Read Keys In Reverse Order<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>If you need descending key order, reverse the key view or use reversed iteration.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">from sortedcontainers import SortedDict\n\nscores = SortedDict({\"maya\": 92, \"noah\": 85, \"iris\": 97})\n\nfor name in reversed(scores):\n    print(name, scores[name])\n<\/code><\/pre>\n<\/div>\n<p>Reverse iteration still follows the sorted key order, just from highest key to lowest key.<\/p>\n<p>Use reverse order when the newest, largest, or highest-priority key should appear first. Because the mapping is already sorted by key, reversing the traversal expresses that intent directly and avoids a separate descending sort step.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Sort_By_Value_Separately\"><\/span>Sort By Value Separately<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p><code>SortedDict<\/code> sorts by key, not by value. If you need value order, sort the items from a normal dictionary or a <code>SortedDict<\/code> result.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">scores = {\"maya\": 92, \"noah\": 85, \"iris\": 97}\n\nby_score = sorted(scores.items(), key=lambda item: item[1], reverse=True)\n\nprint(by_score)\n<\/code><\/pre>\n<\/div>\n<p>This keeps the purpose clear. Use <code>SortedDict<\/code> for key order. Use <code>sorted()<\/code> with a key function for value order. For conversion patterns, see the <a href=\"https:\/\/www.pythonpool.com\/dictionary-to-list-python\/\">dictionary to list<\/a> guide.<\/p>\n<p>A common mistake is expecting <code>SortedDict<\/code> to rank entries by score, price, length, or another value field. It does not do that automatically. If the rank should be based on a value, keep the mapping simple and sort the items with a dedicated key function at the point where you need ranked output.<\/p>\n<p><code>SortedDict<\/code> is a good fit when sorted key order is required throughout the program. It supports familiar dictionary operations while maintaining sorted keys, plus useful indexed and bisect-style helpers. If you only need one sorted output, a normal dictionary plus <code>sorted()<\/code> is usually simpler.<\/p>\n<figure class=\"pythonpool-article-visual pythonpool-supporting-visual\"><img src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/sorteddict-update-b211.png\" alt=\"Python Pool infographic mapping an insertion, update, sorted position, and lookup\" width=\"1536\" height=\"1054\" loading=\"lazy\" decoding=\"async\"><figcaption>Updates preserve key ordering while changing mapping contents.<\/figcaption><\/figure>\n<h2><span class=\"ez-toc-section\" id=\"Install_And_Create_SortedDict\"><\/span>Install And Create SortedDict<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>SortedDict is provided by the external sortedcontainers package. Import it explicitly and choose a key ordering that all keys can support. Mixed incomparable key types will fail when the structure needs to order them.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">from sortedcontainers import SortedDict\n\nprices = SortedDict({\"apple\": 2, \"banana\": 1, \"pear\": 3})\nprint(prices)\nprint(list(prices))<\/code><\/pre>\n<\/div>\n<h2><span class=\"ez-toc-section\" id=\"Add_Update_And_Delete_Keys\"><\/span>Add, Update, And Delete Keys<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The mapping interface resembles dict: assignment adds or updates a key, del removes it, and pop() returns a value. The difference is that iteration and ordered key methods reflect sorted key order after every change.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">from sortedcontainers import SortedDict\n\nvalues = SortedDict()\nvalues[3] = \"three\"\nvalues[1] = \"one\"\nvalues[2] = \"two\"\nprint(list(values.items()))\nprint(values.pop(2))<\/code><\/pre>\n<\/div>\n<figure class=\"pythonpool-article-visual pythonpool-supporting-visual\"><img src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/sorteddict-check-b211.png\" alt=\"Python Pool infographic testing dependencies, missing keys, mutation, performance, and validation\" width=\"1536\" height=\"1054\" loading=\"lazy\" decoding=\"async\"><figcaption>Check dependency version, missing-key behavior, mutation, performance tradeoffs, and API semantics.<\/figcaption><\/figure>\n<h2><span class=\"ez-toc-section\" id=\"Use_Ordered_Navigation\"><\/span>Use Ordered Navigation<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>SortedDict exposes keys(), values(), and items() views plus index-oriented access patterns that are useful for predecessor, successor, and range queries. Choose these operations when the ordering is part of the data structure&#8217;s job rather than sorting a mapping once for display.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">from sortedcontainers import SortedDict\n\nvalues = SortedDict({10: \"a\", 20: \"b\", 30: \"c\"})\nprint(values.keys()[1])\nprint(values.keys().bisect_left(25))\nprint(list(values.irange(10, 25)))<\/code><\/pre>\n<\/div>\n<h2><span class=\"ez-toc-section\" id=\"Compare_With_A_Built-In_dict\"><\/span>Compare With A Built-In dict<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Modern dict preserves insertion order, but it does not automatically reorder keys after a new key is inserted. Converting dict.items() through sorted() is fine for a one-time report. SortedDict is justified when sorted access is repeated and the dependency is acceptable for the project.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">from sortedcontainers import SortedDict\n\nplain = {3: \"three\", 1: \"one\"}\nordered_once = dict(sorted(plain.items()))\nmaintained = SortedDict(plain)\nprint(ordered_once)\nprint(maintained)<\/code><\/pre>\n<\/div>\n<p>The official <a href=\"https:\/\/grantjenks.com\/docs\/sortedcontainers\/sorteddict.html\">SortedDict documentation<\/a> defines its sorted mapping operations, views, and ordered navigation. Keep the package version pinned and test key ordering as part of the application contract.<\/p>\n<p>For nearby mapping patterns, compare <a href=\"https:\/\/www.pythonpool.com\/sort-dictionary-by-key-in-python\/\">sorting a dictionary by key<\/a>, <a href=\"https:\/\/www.pythonpool.com\/python-ordereddict\/\">OrderedDict operations<\/a>, and <a href=\"https:\/\/www.pythonpool.com\/python-hashmaps\/\">hashmap fundamentals<\/a> before choosing a data structure for ordered access.<\/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_SortedDict_in_Python\"><\/span>What is SortedDict in Python?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>SortedDict is a mapping from the sortedcontainers package that maintains its keys in sorted order and supports ordered access.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"How_is_SortedDict_different_from_dict\"><\/span>How is SortedDict different from dict?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>dict preserves insertion order but does not sort keys automatically; SortedDict maintains sorted-key behavior and exposes ordered operations.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"How_do_I_install_SortedDict\"><\/span>How do I install SortedDict?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Install the sortedcontainers package with pip, then import SortedDict from sortedcontainers.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"When_should_I_use_SortedDict\"><\/span>When should I use SortedDict?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Use it when frequent ordered-key queries, predecessor or successor access, or range-style operations justify the dependency; use dict for ordinary key lookup.<\/p>\n<p><script type=\"application\/ld+json\">{\"@context\":\"https:\/\/schema.org\",\"@type\":\"FAQPage\",\"mainEntity\":[{\"@type\":\"Question\",\"name\":\"What is SortedDict in Python?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"SortedDict is a mapping from the sortedcontainers package that maintains its keys in sorted order and supports ordered access.\"}},{\"@type\":\"Question\",\"name\":\"How is SortedDict different from dict?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"dict preserves insertion order but does not sort keys automatically; SortedDict maintains sorted-key behavior and exposes ordered operations.\"}},{\"@type\":\"Question\",\"name\":\"How do I install SortedDict?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Install the sortedcontainers package with pip, then import SortedDict from sortedcontainers.\"}},{\"@type\":\"Question\",\"name\":\"When should I use SortedDict?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Use it when frequent ordered-key queries, predecessor or successor access, or range-style operations justify the dependency; use dict for ordinary key lookup.\"}}]}<\/script><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Use SortedDict from sortedcontainers for sorted keys, range-friendly access, updates, deletion, and a clear comparison with dict.<\/p>\n","protected":false},"author":1,"featured_media":33483,"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":[5486,5487,5484,5485,5488],"class_list":["post-23434","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tutorials","tag-python-sorted-dict-bisect","tag-python-sorted-dict-reverse","tag-python-sorteddict-example","tag-python-sorteddict-implementation","tag-python-sorteddict-time-complexity","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 SortedDict: Sorted Containers, Keys, and Updates<\/title>\n<meta name=\"description\" content=\"Use SortedDict from sortedcontainers for sorted keys, range-friendly access, updates, deletion, and a clear comparison with dict.\" \/>\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-sorteddict\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python SortedDict: Sorted Containers, Keys, and Updates\" \/>\n<meta property=\"og:description\" content=\"Use SortedDict from sortedcontainers for sorted keys, range-friendly access, updates, deletion, and a clear comparison with dict.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pythonpool.com\/python-sorteddict\/\" \/>\n<meta property=\"og:site_name\" content=\"Python Pool\" \/>\n<meta property=\"article:published_time\" content=\"2022-11-13T15:34:35+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-07-13T07:10:27+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-sorteddict.png\" \/>\n<meta name=\"author\" content=\"Python Pool\" \/>\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-sorteddict.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=\"Python Pool\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-sorteddict\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-sorteddict\\\/\"},\"author\":{\"name\":\"Python Pool\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#\\\/schema\\\/person\\\/f87448ee54c0ffd2889fbf2408c18998\"},\"headline\":\"Python SortedDict: Sorted Containers, Keys, and Updates\",\"datePublished\":\"2022-11-13T15:34:35+00:00\",\"dateModified\":\"2026-07-13T07:10:27+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-sorteddict\\\/\"},\"wordCount\":1255,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-sorteddict\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2026\\\/07\\\/python-sorteddict-guide-pythonpool.png\",\"keywords\":[\"python sorted dict bisect\",\"python sorted dict reverse\",\"python sorteddict example\",\"python sorteddict implementation\",\"python sorteddict time complexity\"],\"articleSection\":[\"Tutorials\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.pythonpool.com\\\/python-sorteddict\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-sorteddict\\\/\",\"url\":\"https:\\\/\\\/www.pythonpool.com\\\/python-sorteddict\\\/\",\"name\":\"Python SortedDict: Sorted Containers, Keys, and Updates\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-sorteddict\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-sorteddict\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2026\\\/07\\\/python-sorteddict-guide-pythonpool.png\",\"datePublished\":\"2022-11-13T15:34:35+00:00\",\"dateModified\":\"2026-07-13T07:10:27+00:00\",\"description\":\"Use SortedDict from sortedcontainers for sorted keys, range-friendly access, updates, deletion, and a clear comparison with dict.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-sorteddict\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.pythonpool.com\\\/python-sorteddict\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-sorteddict\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2026\\\/07\\\/python-sorteddict-guide-pythonpool.png\",\"contentUrl\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2026\\\/07\\\/python-sorteddict-guide-pythonpool.png\",\"width\":1350,\"height\":650,\"caption\":\"Python SortedDict guide showing sorted keys and dictionary operations\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-sorteddict\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.pythonpool.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python SortedDict: Sorted Containers, Keys, and Updates\"}]},{\"@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\\\/f87448ee54c0ffd2889fbf2408c18998\",\"name\":\"Python Pool\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/fdd3cb9ad7f560324dfd481989550aa8ffce84388fd253c42beca35c999d3108?s=96&d=wavatar&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/fdd3cb9ad7f560324dfd481989550aa8ffce84388fd253c42beca35c999d3108?s=96&d=wavatar&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/fdd3cb9ad7f560324dfd481989550aa8ffce84388fd253c42beca35c999d3108?s=96&d=wavatar&r=g\",\"caption\":\"Python Pool\"}}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Python SortedDict: Sorted Containers, Keys, and Updates","description":"Use SortedDict from sortedcontainers for sorted keys, range-friendly access, updates, deletion, and a clear comparison with dict.","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-sorteddict\/","og_locale":"en_US","og_type":"article","og_title":"Python SortedDict: Sorted Containers, Keys, and Updates","og_description":"Use SortedDict from sortedcontainers for sorted keys, range-friendly access, updates, deletion, and a clear comparison with dict.","og_url":"https:\/\/www.pythonpool.com\/python-sorteddict\/","og_site_name":"Python Pool","article_published_time":"2022-11-13T15:34:35+00:00","article_modified_time":"2026-07-13T07:10:27+00:00","og_image":[{"url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-sorteddict.png","type":"","width":"","height":""}],"author":"Python Pool","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-sorteddict.png","twitter_creator":"@pythonpool","twitter_site":"@pythonpool","twitter_misc":{"Written by":"Python Pool","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.pythonpool.com\/python-sorteddict\/#article","isPartOf":{"@id":"https:\/\/www.pythonpool.com\/python-sorteddict\/"},"author":{"name":"Python Pool","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/f87448ee54c0ffd2889fbf2408c18998"},"headline":"Python SortedDict: Sorted Containers, Keys, and Updates","datePublished":"2022-11-13T15:34:35+00:00","dateModified":"2026-07-13T07:10:27+00:00","mainEntityOfPage":{"@id":"https:\/\/www.pythonpool.com\/python-sorteddict\/"},"wordCount":1255,"commentCount":0,"publisher":{"@id":"https:\/\/www.pythonpool.com\/#organization"},"image":{"@id":"https:\/\/www.pythonpool.com\/python-sorteddict\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-sorteddict-guide-pythonpool.png","keywords":["python sorted dict bisect","python sorted dict reverse","python sorteddict example","python sorteddict implementation","python sorteddict time complexity"],"articleSection":["Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.pythonpool.com\/python-sorteddict\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.pythonpool.com\/python-sorteddict\/","url":"https:\/\/www.pythonpool.com\/python-sorteddict\/","name":"Python SortedDict: Sorted Containers, Keys, and Updates","isPartOf":{"@id":"https:\/\/www.pythonpool.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.pythonpool.com\/python-sorteddict\/#primaryimage"},"image":{"@id":"https:\/\/www.pythonpool.com\/python-sorteddict\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-sorteddict-guide-pythonpool.png","datePublished":"2022-11-13T15:34:35+00:00","dateModified":"2026-07-13T07:10:27+00:00","description":"Use SortedDict from sortedcontainers for sorted keys, range-friendly access, updates, deletion, and a clear comparison with dict.","breadcrumb":{"@id":"https:\/\/www.pythonpool.com\/python-sorteddict\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pythonpool.com\/python-sorteddict\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/python-sorteddict\/#primaryimage","url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-sorteddict-guide-pythonpool.png","contentUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-sorteddict-guide-pythonpool.png","width":1350,"height":650,"caption":"Python SortedDict guide showing sorted keys and dictionary operations"},{"@type":"BreadcrumbList","@id":"https:\/\/www.pythonpool.com\/python-sorteddict\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.pythonpool.com\/"},{"@type":"ListItem","position":2,"name":"Python SortedDict: Sorted Containers, Keys, and Updates"}]},{"@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\/f87448ee54c0ffd2889fbf2408c18998","name":"Python Pool","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/fdd3cb9ad7f560324dfd481989550aa8ffce84388fd253c42beca35c999d3108?s=96&d=wavatar&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/fdd3cb9ad7f560324dfd481989550aa8ffce84388fd253c42beca35c999d3108?s=96&d=wavatar&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/fdd3cb9ad7f560324dfd481989550aa8ffce84388fd253c42beca35c999d3108?s=96&d=wavatar&r=g","caption":"Python Pool"}}]}},"_links":{"self":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/23434","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\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/comments?post=23434"}],"version-history":[{"count":22,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/23434\/revisions"}],"predecessor-version":[{"id":41891,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/23434\/revisions\/41891"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/media\/33483"}],"wp:attachment":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/media?parent=23434"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/categories?post=23434"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/tags?post=23434"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}