{"id":28853,"date":"2023-03-05T18:18:13","date_gmt":"2023-03-05T12:48:13","guid":{"rendered":"https:\/\/copyassignment.com\/?p=28853"},"modified":"2023-03-05T18:18:15","modified_gmt":"2023-03-05T12:48:15","slug":"python-how-to-sort-a-dictionary-by-value","status":"publish","type":"post","link":"https:\/\/copyassignment.com\/python-how-to-sort-a-dictionary-by-value\/","title":{"rendered":"Python | How to sort a dictionary by value?"},"content":{"rendered":"\n<p>Sorting a dictionary by value is a common task in Python and we will see different ways of how can accomplish this task. Also, sorting a dictionary with respect to keys is simpler than sorting it by values.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Method 1: Sort a dictionary using for loop<\/h2>\n\n\n\n<p>This is the most straightforward method to sort a dictionary by its value. In this approach, we first sort the values of the dictionary in ascending order. We then loop through the sorted values and for each sorted value, we loop through the keys of the dictionary when we find a key with a value that matches the current sorted value, we add this key-value pair to the new dictionary that we have created to store the answer. In this way, we keep on adding all the key-value pairs in the newly created dictionary and finally print the sorted dictionary.<\/p>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"python\" data-theme=\"xcode\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">dict1 = {\"Python\":3, \"Java\": 2, \"JavaScript\": 1, \"C++\": 5, \"Ruby\":4}\nsorted_values = sorted(dict1.values()) # Sort the values of original dictionary in ascending order\nsorted_dict = {}   #  Create a new dictionary to store the final result\n\nfor i in sorted_values:      \n    for k in dict1.keys():        \n        if dict1[k] == i:  # if the value is same as the sorted value\n            sorted_dict[k] = dict1[k]  # add it to the new dictionary          \n            break\nprint(sorted_dict)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>{'JavaScript': 1, 'Java': 2, 'Python': 3, 'Ruby': 4, 'C++': 5}<\/strong><\/pre>\n\n\n\n<script async=\"\" src=\"https:\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js\"><\/script>\n<ins class=\"adsbygoogle\" style=\"display:block; text-align:center;\" data-ad-layout=\"in-article\" data-ad-format=\"fluid\" data-ad-client=\"ca-pub-9886351916045880\" data-ad-slot=\"2002566052\"><\/ins>\n<script>\n     (adsbygoogle = window.adsbygoogle || []).push({});\n<\/script>\n\n\n\n<h2 class=\"wp-block-heading\">Method 2: Using bubble sort by converting the dictionary to list<\/h2>\n\n\n\n<p>In this approach, we convert the dictionary to a list and apply the bubble sort algorithm to the list to sort the element. But this is not that straightforward as the list contains tuples that store the key-value pairs in it. <\/p>\n\n\n\n<p>Let\u2019s try to print and see what the list looks like when we convert it from the dictionary.<\/p>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"python\" data-theme=\"xcode\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">langdict={\"Python\":3, \"Java\": 2, \"JavaScript\": 1, \"C++\": 5, \"Ruby\":4}\nlanglist=list(langdict.items()) # convert dictionary to list\nprint(langlist)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>[('Python', 3), ('Java', 2), ('JavaScript', 1), ('C++', 5), ('Ruby', 4)]<\/strong><\/pre>\n\n\n\n<p>As you can see the list contains all the key-value pairs in the form of a tuple. So if we want to perform bubble sort on this, we have to use the key index as 0 and the value index as 1 for each tuple in the list.<\/p>\n\n\n\n<p>Now, Let\u2019s understand the working of the below code to perform bubble sort-<\/p>\n\n\n\n<p>First, we convert the dictionary to a list of tuples called <em><strong>langlist<\/strong><\/em> using the <em><strong>list()<\/strong><\/em> method. Then we use two nested for loops to iterate through the list and compare each value with every other value in the list. &nbsp;If the value at index <em><strong>&#8220;i&#8221;<\/strong><\/em> is greater than the value at index &#8220;j&#8221;, we swap the two values. After comparing all the values with each other and placing them in the correct position, we convert the sorted list back into a dictionary using the dict() method and store it in a variable called sortdict, and finally, print it.<\/p>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"python\" data-theme=\"xcode\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">langdict={\"Python\":3, \"Java\": 2, \"JavaScript\": 1, \"C++\": 5, \"Ruby\":4}\nlanglist=list(langdict.items()) # convert dictionary to list\nprint(langlist)\nl=len(langlist)\nfor i in range(l-1): # for i in range(4) 0,1,2,3\n  for j in range(i+1,l): # for j in range(1,5) 1,2,3,4\n    if langlist[i][1]>langlist[j][1]: # langlist[0][1]>langlist[1][1] 3>2\n          t=langlist[i]\n          print(t)\n          langlist[i]=langlist[j]\n          langlist[j]=t\nsortdict=dict(langlist) # convert list to dictionary\nprint(sortdict)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>{'JavaScript': 1, 'Java': 2, 'Python': 3, 'Ruby': 4, 'C++': 5}<\/strong><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Method 3: Using the sorted() function<\/h2>\n\n\n\n<p>We can also use the inbuilt <strong><em>sorted()<\/em><\/strong> function of Python to sort the dictionary by its value. The <em>sorted()<\/em> function in Python is used to sort iterable such as a list or dictionary and it returns a sorted list of all the items.&nbsp;<\/p>\n\n\n\n<p>The sorted() function takes three arguments &#8211;&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><em>iterable<\/em><\/strong> &#8211; like a list, tuple, or dictionary<\/li>\n\n\n\n<li><strong><em>key<\/em><\/strong> &#8211; it is an optional value that can be a function that helps in applying custom comparison(we will use this to sort the dictionary by values)<\/li>\n\n\n\n<li><strong><em>reverse<\/em><\/strong> &#8211; It is used to sort the iterable in ascending or descending order.&nbsp; it Is also an optional value and it can be either true or false.<\/li>\n<\/ul>\n\n\n\n<p>Here, we will use different methods of passing the <strong><em>key<\/em><\/strong> argument to the <strong><em>sorted()<\/em><\/strong> function to sort a dictionary by value.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3.1 Using the lambda function<\/h3>\n\n\n\n<p>The lambda function is a small anonymous function which means it does not have any name. We can pass a lambda function which contains the logic for the comparison of values as the <strong><em>key<\/em><\/strong> argument in <strong><em>sorted()<\/em><\/strong> function like this<\/p>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"python\" data-theme=\"xcode\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">langdict={\"Python\":3, \"Java\": 2, \"JavaScript\": 1, \"C++\": 5, \"Ruby\":4}\nlanglist = sorted(langdict.items(), key=lambda x:x[1])\nsortdict = dict(langlist)\nprint(sortdict)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>{'JavaScript': 1, 'Java': 2, 'Python': 3, 'Ruby': 4, 'C++': 5}<\/strong><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">3.2 Using operator.itemgetter() method<\/h3>\n\n\n\n<p>The operator module is a built-in module in Python that provides a set of functions like itemgetter() that can be used to perform different operations. For example, rather than using the \u201c+\u201d operator, we can use the add() function of the operator module to add two numbers. <\/p>\n\n\n\n<p>In this approach, we will use the <strong><em>operator.itemgetter()<\/em><\/strong> method to write the comparison logic. Here, <strong><em>itemgetter(1)<\/em><\/strong> will get the value of each key-value pair in the dictionary.<\/p>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"python\" data-theme=\"xcode\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">import operator\nlangdict={\"Python\":3, \"Java\": 2, \"JavaScript\": 1, \"C++\": 5, \"Ruby\":4}\nlanglist= sorted(langdict.items(), key=operator.itemgetter(1))\nsortdict=dict(langlist)\nprint(sortdict)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>{'JavaScript': 1, 'Java': 2, 'Python': 3, 'Ruby': 4, 'C++': 5}<\/strong><\/pre>\n\n\n\n<script async=\"\" src=\"https:\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js\"><\/script>\n<ins class=\"adsbygoogle\" style=\"display:block; text-align:center;\" data-ad-layout=\"in-article\" data-ad-format=\"fluid\" data-ad-client=\"ca-pub-9886351916045880\" data-ad-slot=\"2002566052\"><\/ins>\n<script>\n     (adsbygoogle = window.adsbygoogle || []).push({});\n<\/script>\n\n\n\n<h3 class=\"wp-block-heading\">3.3 Using list comprehension with sorted() function<\/h3>\n\n\n\n<p>We can also use dict.items() method with the sorted() function to sort a dictionary by value.<\/p>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"python\" data-theme=\"xcode\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">langdict={\"Python\":3, \"Java\": 2, \"JavaScript\": 1, \"C++\": 5, \"Ruby\":4}\nlanglist=sorted((value, key) for (key,value) in langdict.items())\nsortdict=dict([(k,v) for v,k in langlist])\nprint(sortdict)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>{'JavaScript': 1, 'Java': 2, 'Python': 3, 'Ruby': 4, 'C++': 5}<\/strong><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">3.4 Using dict.get() method with sorted()<\/h3>\n\n\n\n<p>In Python, <strong><em>dict.get()<\/em><\/strong> is a method that can be used to get the corresponding values of each key in a dictionary. This function returns the value associated with that key if the key is found in the dictionary otherwise it returns None. We can use dict.get() as the comparison argument in the sorted() function to sort a dictionary by value.<\/p>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"python\" data-theme=\"xcode\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">langdict={\"Python\":3, \"Java\": 2, \"JavaScript\": 1, \"C++\": 5, \"Ruby\":4}\nsorted_dict = {}\nsorted_keys = sorted(langdict, key=langdict.get)  # sorted keys\nfor w in sorted_keys:      # iterate over the sorted keys\n  sorted_dict[w] = langdict[w]  # add the sorted key-value pair to the new dictionary\nprint(sorted_dict)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>{'JavaScript': 1, 'Java': 2, 'Python': 3, 'Ruby': 4, 'C++': 5}<\/strong><\/pre>\n\n\n\n<div style=\"text-align:center\" class=\"wp-block-atomic-blocks-ab-button ab-block-button\"><a href=\"https:\/\/stackoverflow.com\/questions\/613183\/how-do-i-sort-a-dictionary-by-value\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"ab-button ab-button-shape-rounded ab-button-size-medium\" style=\"color:#ffffff;background-color:#3373dc\">Click here to discuss more on this topic<\/a><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this article, we explored various approaches like using built-in functions as well as sorting algorithms like bubble sort to sort a dictionary by value. I hope you find this article helpful.<\/p>\n\n\n\n<script async src=\"https:\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js?client=ca-pub-9886351916045880\"\n     crossorigin=\"anonymous\"><\/script>\n<ins class=\"adsbygoogle\"\n     style=\"display:block\"\n     data-ad-format=\"autorelaxed\"\n     data-ad-client=\"ca-pub-9886351916045880\"\n     data-ad-slot=\"7933252109\"><\/ins>\n<script>\n     (adsbygoogle = window.adsbygoogle || []).push({});\n<\/script>\n\n\n\n<p>Thank you for visiting\u00a0<a href=\"https:\/\/copyassignment.com\/\">our website<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>Also read:<\/strong><\/p>\n\n\n<ul class=\"wp-block-latest-posts__list is-grid columns-3 wp-block-latest-posts\"><li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-asking-the-user-for-input-until-they-give-a-valid-response\/\">Python | Asking the user for input until they give a valid response<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-how-to-iterate-through-two-lists-in-parallel\/\">Python | How to iterate through two lists in parallel?<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-how-to-sort-a-dictionary-by-value\/\">Python | How to sort a dictionary by value?<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-remove-items-from-a-list-while-iterating\/\">Python | Remove items from a list while iterating<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-how-to-get-dictionary-keys-as-a-list\/\">Python | How to get dictionary keys as a list<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/how-to-represent-enum-in-python\/\">How to represent Enum in Python?<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/5-methods-flatten-a-list-of-lists-convert-nested-list-into-a-single-list-in-python\/\">5 methods | Flatten a list of lists | Convert nested list into a single list in Python<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/what-does-if-__name__-__main__-do-in-python\/\">What does if __name__ == __main__ do in Python?<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-crud-operations-in-mongodb\/\">Python | CRUD operations in MongoDB<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/create-your-own-chatgpt-with-python\/\">Create your own ChatGPT with\u00a0Python<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/filter-list-in-python-10-methods\/\">Filter List in Python | 10 methods<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/radha-krishna-using-python-turtle\/\">Radha Krishna using Python Turtle<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/yield-keyword-in-python\/\">Yield Keyword in Python<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-programming-examples-fundamental-programs-in-python\/\">Python Programming Examples | Fundamental Programs in Python<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-delete-object-of-a-class\/\">Python | Delete object of a class<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-modify-properties-of-objects\/\">Python | Modify properties of objects\u00a0<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-classmethod\/\">Python classmethod<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-create-a-class-that-takes-2-parameters-print-both-parameters\/\">Python | Create a class that takes 2 parameters, print both parameters<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-create-a-class-create-an-object-of-the-class-access-and-print-property-value\/\">Python | Create a class, create an object of the class, access, and print property value<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-calculator-using-lambda\/\">Python | Calculator using lambda<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-multiply-numbers-using-lambda\/\">Python | Multiply numbers using lambda<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-print-namaste-using-lambda\/\">Python | Print Namaste using lambda<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/iterate-over-a-string-in-python\/\">Iterate over a string in Python<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-join-join-list-of-strings\/\">Python | join() | Join list of strings<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-isalnum-method-check-if-a-string-consists-only-of-alphabetical-characters-or-numerical-digits\/\">Python | isalnum() method | check if a string consists only of alphabetical characters or numerical digits<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-isupper-and-islower-methods-to-check-if-a-string-is-in-all-uppercase-or-lowercase-letters\/\">Python | isupper() and islower() methods to check if a string is in all uppercase or lowercase letters<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-count-substring-in-a-string-count-method\/\">Python | count substring in a String | count() method<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-enumerate-on-string-get-index-and-element\/\">Python | enumerate() on String | Get index and element<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/python-convert-a-string-to-list-using-list-method\/\">Python | Convert a String to list using list() method<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/copyassignment.com\/eulers-number-in-python\/\">Euler&#8217;s Number in Python<\/a><\/li>\n<\/ul>","protected":false},"excerpt":{"rendered":"<p>Sorting a dictionary by value is a common task in Python and we will see different ways of how can accomplish this task. Also, sorting&#8230;<\/p>\n","protected":false},"author":62,"featured_media":28895,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[22,1928],"tags":[],"class_list":["post-28853","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-allcategorites","category-python-short-tutorial","wpcat-22-id","wpcat-1928-id"],"_links":{"self":[{"href":"https:\/\/copyassignment.com\/wp-json\/wp\/v2\/posts\/28853","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/copyassignment.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/copyassignment.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/copyassignment.com\/wp-json\/wp\/v2\/users\/62"}],"replies":[{"embeddable":true,"href":"https:\/\/copyassignment.com\/wp-json\/wp\/v2\/comments?post=28853"}],"version-history":[{"count":0,"href":"https:\/\/copyassignment.com\/wp-json\/wp\/v2\/posts\/28853\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/copyassignment.com\/wp-json\/wp\/v2\/media\/28895"}],"wp:attachment":[{"href":"https:\/\/copyassignment.com\/wp-json\/wp\/v2\/media?parent=28853"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/copyassignment.com\/wp-json\/wp\/v2\/categories?post=28853"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/copyassignment.com\/wp-json\/wp\/v2\/tags?post=28853"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}