{"id":4360,"date":"2020-03-28T10:36:50","date_gmt":"2020-03-28T10:36:50","guid":{"rendered":"https:\/\/www.askpython.com\/?p=4360"},"modified":"2020-03-28T11:20:33","modified_gmt":"2020-03-28T11:20:33","slug":"sort-a-dictionary-in-python","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/dictionary\/sort-a-dictionary-in-python","title":{"rendered":"How to Sort a Dictionary in Python?"},"content":{"rendered":"\n<p>There are different ways through which we can sort a Dictionary in Python. There are many ways, depending on whether you want to sort it by key or by value.<\/p>\n\n\n\n<p>Let&#8217;s take a look at some of them in the article!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Sort a Dictionary in Python by Value<\/h2>\n\n\n\n<p>If we want to sort a Dictionary in Python by value, there are a few ways using which we can achieve this.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Method 1: Using sorted() using a lambda (Recommended for Python 3.6+)<\/h3>\n\n\n\n<p>On newer versions on Python (<strong>Python 3.6<\/strong> and above), we can use a lambda on the <code>sorted()<\/code> method to sort a dictionary in Python.<\/p>\n\n\n\n<p>We will sort the <code>dict.items()<\/code>, using the key as a lambda.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nmy_dict = {1: 2, 2: 10, &quot;Hello&quot;: 1234}\n\nprint({key: value for key, value in sorted(my_dict.items(), key=lambda item: item&#x5B;1])})\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n{1: 2, 2: 10, &#039;Hello&#039;: 1234}\n<\/pre><\/div>\n\n\n<p>Indeed, we can see that our new dictionary has been sorted based on the value!<\/p>\n\n\n\n<p>The reason why this method works on Python 3.6+ is that Dictionaries in the new versions of Python are now an ordered datatype.<\/p>\n\n\n\n<p>This means that we can enumerate a dictionary as a list of items, and also perform operations that can change the order, such as sorting it.<\/p>\n\n\n\n<p>But fear not. If you have an older version of Python, keep reading. We&#8217;ll show you another way to deal with this!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Method 2: Using sorted() on older versions of Python<\/h3>\n\n\n\n<p>We can still use <code>sorted()<\/code> to sort the dictionary. But we something to make the Dictionary into an ordered type. The <code>operator<\/code> module has that, using <code>operator.itemgetter(idx)<\/code>.<\/p>\n\n\n\n<p>The below snippet will sort our dictionary by value:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport operator\n\nmy_dict = {1: 2, 2: 10, &quot;Hello&quot;: 1234}\n\nsorted_dict = sorted(my_dict.items(), key=operator.itemgetter(1))\n\nprint(sorted_dict)\n<\/pre><\/div>\n\n\n<p>More specifically, we form a sorted list using <code>sorted(dict.items()<\/code>), and pass <code>operator.itemgetter(1)<\/code> to it (Since the value is at index 1).<\/p>\n\n\n\n<p>This will construct a callable that will grab that first element from the items list. We do this at every iteration, thereby getting a sorted dictionary!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Sort a Dictionary in Python by Key<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Method 1: Use operator.itemgetter() (Recommended method for older versions of Python)<\/h3>\n\n\n\n<p>Now, if you want to sort a Dictionary by Key, we can use the <code>operator<\/code> method, like in the last section. The only change that we have to make is to sort the list based on keys now, so we call <code>operator.itemgetter(0)<\/code>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport operator\n\nmy_dict = {2: 10, 1: 2, -3: 1234}\n\n# Sort the Dict based on keys\nsorted_dict = dict(sorted(my_dict.items(), key=operator.itemgetter(0)))\n\nprint(sorted_dict)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n{-3: 1234, 1: 2, 2: 10}\n<\/pre><\/div>\n\n\n<p>Indeed, the dictionary has been sorted based on the Key now!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Method 2: Use sorted() with a lambda (Recommended method for Python 3.6+)<\/h3>\n\n\n\n<p>We can again use the <code>sorted()<\/code> method, with a lambda, on newer versions of Python.<\/p>\n\n\n\n<p>Again, this is the same as before, but we&#8217;ll be now sorting based on value.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nmy_dict = {2: 10, 1: 2, -3: 1234}\nsorted_dict = dict(sorted(my_dict.items(), key=lambda item: item&#x5B;0]))\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n{-3: 1234, 1: 2, 2: 10}\n<\/pre><\/div>\n\n\n<p>Again, the output is the same as before.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this article, we learned how we could sort a Dictionary in Python; both by key and by value, using different approaches.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/stackoverflow.com\/questions\/613183\/how-do-i-sort-a-dictionary-by-value\" class=\"rank-math-link\" target=\"_blank\" rel=\"noopener\">StackOverflow Question<\/a> on Sorting a Dictionary by value<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n","protected":false},"excerpt":{"rendered":"<p>There are different ways through which we can sort a Dictionary in Python. There are many ways, depending on whether you want to sort it by key or by value. Let&#8217;s take a look at some of them in the article! Sort a Dictionary in Python by Value If we want to sort a Dictionary [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":4381,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5],"tags":[],"class_list":["post-4360","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-dictionary"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/4360","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=4360"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/4360\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/4381"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=4360"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=4360"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=4360"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}