{"id":3446,"date":"2021-04-23T13:25:35","date_gmt":"2021-04-23T07:55:35","guid":{"rendered":"https:\/\/python-programs.com\/?p=3446"},"modified":"2021-11-22T18:44:54","modified_gmt":"2021-11-22T13:14:54","slug":"python-how-to-sort-a-dictionary-by-key-or-value","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-how-to-sort-a-dictionary-by-key-or-value\/","title":{"rendered":"Python : How to Sort a Dictionary by Key or Value ?"},"content":{"rendered":"

Dictionaries are the implementation by Python of a data structure associative array. A dictionary is a collection of pairs of key values. A key pair and its associated value represent each key pair.<\/p>\n

The list of key value pairs in curly braces that is separated by comma defines a dictionary. Column ‘:’ separates the value of each key.<\/p>\n

A dictionary cannot be sorted only to get a representation of the sorted dictionary. Inherently, dictionaries are orderless, but not other types, including lists and tuples. Therefore, you need an ordered data type, which is a list\u2014probably a list of tuples.<\/p>\n

In this post, we will look at how to sort a dictionary by key or value<\/p>\n

Examples:<\/strong><\/p>\n

By keys<\/h3>\n

Input:<\/strong><\/p>\n

dictionary = {'this': 200, 'is':100, 'BTechGeeks':300}<\/pre>\n

Output:<\/strong><\/p>\n

BTechGeeks : 300\r\nis : 100\r\nthis :200<\/pre>\n

Input:<\/strong><\/p>\n

dictionary = {'this': 100, 'is':200, 'BTechGeeks':300}<\/pre>\n

Output:<\/strong><\/p>\n

is : 100\r\nthis : 200\r\nBTechGeeks : 300<\/pre>\n

Sort a Dictionary by Key\/Value<\/h2>\n

There are several ways to sort a dictionary by key or value some of them are:<\/p>\n