Menu Close

How To Sort Python Dictionary by Key or Value

How to sort Python dictionary by key or value

In this article, we are going to learn how to sort Python Dictionary by key or value with the help of various examples. Sometimes you want to sort your Python dictionaries by specific key or value Then you can follow all the methods which we will learn throughout the program.

To sort the Python dictionary by value or key we will go through the various methods to sort the Dictionaries so that you don’t have any confusion regarding how to sort Python dictionary by key or value.

Before going through this article, first of all, we will are going to know a little bit about Python Dictionary.

What is Python Dictionary?

Dictionary is one of the most important data types in Python. Python dictionary contains unordered collections of items, that’s why Python dictionary can not sort the keys or values.
Dictionaries in Python is made using key-value pair where value can be access by their corresponding key.

In this guide, we will demonstrate some custom ways as well pre-defined methods to sort the Python dictionary.

Why do you need to sort the Python dictionary?

As a developer when you are going to create the REST APIs, Then the client or someone (who consumes your API ) requirement is that your response body’s key should be sorted.
At that time you have to sort your Python dictionary key just before response return.

Sort Python Dictionary By Key

Here we will use the Python sorted function to sort the Python dictionary. the sorted() function is a built-in function in Python that returns a new list containing all the items from an iterable in ascending order which is usually not our desired output. Sometimes our requirement may be, keys would be sorted or sometimes values should be sorted.

Input Value:


{
    "age": 21,
    "course": "BCA",
    "name": "Vishvajit",
    "address": "Noida",
    "marks": 430,
    "zip_code": 2013089
  }

Desired Output


{
  "address": "Noida",
  "age": 21,
  "course": "BCA",
  "marks": 430,
  "name": "Vishvajit",
  "zip_code": 2013089
}

Python Script – Method 1:


from collections import OrderedDict

# python unordered dictionary
student = {
    "age": 21,
    "course": "BCA",
    "name": "Vishvajit",
    "address": "Noida",
    "marks": 430,
    "zip_code": 2013089
  }

# make OrderedDict() object
new_dict = OrderedDict()

# sort the dictionary by key - it will return lst of tuple and each tuple contains key and their value
sorted_keys_with_values = sorted(student.items())
print(sorted_keys_with_values)

# make a dictionary
for i in sorted_keys_with_values:
  new_dict[i[0]] = i[1]

# new_dict is also a Python dictionary so you can perform all the dictionary operations on it
print(new_dict)

# convert new_dict to proper dictionary structure
print(dict(new_dict))

Output


[('address', 'Noida'), ('age', 21), ('course', 'BCA'), ('marks', 430), ('name', 'Vishvajit'), ('zip_code', 2013089)]
OrderedDict([('address', 'Noida'), ('age', 21), ('course', 'BCA'), ('marks', 430), ('name', 'Vishvajit'), ('zip_code', 2013089)])
{'address': 'Noida', 'age': 21, 'course': 'BCA', 'marks': 430, 'name': 'Vishvajit', 'zip_code': 2013089}

Python Script – Method 2:


# python unordered dictionary
student = {
    "age": 21,
    "course": "BCA",
    "name": "Vishvajit",
    "address": "Noida",
    "marks": 430,
    "zip_code": 2013089,
    "country": "India"
}

# sort the dictionary by key - it will return lst of tuple and each tuple contains key and their value
sorted_keys_with_values = sorted(student.items())
print(sorted_keys_with_values)

# dictionary comprehension to make new dict
result = {k: v for k, v in sorted_keys_with_values}
print(result)

Output


{'address': 'Noida', 'age': 21, 'country': 'India', 'course': 'BCA', 'marks': 430, 'name': 'Vishvajit', 'zip_code': 2013089}

Python Script – Method 3:


# python unordered dictionary
student = {
    "age": 21,
    "course": "BCA",
    "name": "Vishvajit",
    "address": "Noida",
    "marks": 430,
    "zip_code": 2013089,
    "country": "India"
}

# sort the dictionary by key - it will return list sorted keys
sorted_keys = sorted(student)
print(sorted_keys)

# dictionary comprehension to make new dict
result = {k: student[k] for k in sorted_keys}
print(result)

Output

{'address': 'Noida', 'age': 21, 'country': 'India', 'course': 'BCA', 'marks': 430, 'name': 'Vishvajit', 'zip_code': 2013089}

Sort Python Dictionary By Value:

Python Script – Method 1:


# python unordered dictionary
student = {
    "age": "21",
    "roll_no": "ST001",
    "course": "BCA",
    "name": "Vishvajit",
    "address": "Noida",
    "country": "India"
}

# sort the dictionary by key - it will return list sorted keys
sorted_keys = sorted(student.items(), key=lambda kv: kv[1])
print(sorted_keys)

# dictionary comprehension to make new dict
result = {k: v for k, v in sorted_keys}
print(result)

Output

{'age': '21', 'course': 'BCA', 'country': 'India', 'address': 'Noida', 'roll_no': 'ST001', 'name': 'Vishvajit'}

Python Script – Method 2:


# python unordered dictionary
student = {
    "age": "21",
    "roll_no": "ST001",
    "course": "BCA",
    "name": "Vishvajit",
    "address": "Noida",
    "country": "India"
}

# sort the dictionary by key - it will return list sorted keys
sorted_keys = sorted(student.items(), key=lambda kv: kv[1])
print(sorted_keys)

# convert sorted_keys to dictionary using dict()
result = dict(sorted_keys)
print(result)

Output

{'age': '21', 'course': 'BCA', 'country': 'India', 'address': 'Noida', 'roll_no': 'ST001', 'name': 'Vishvajit'}

Python Script – Method 3:


from collections import OrderedDict
# python unordered dictionary
student = {
    "age": "21",
    "roll_no": "ST001",
    "course": "BCA",
    "name": "Vishvajit",
    "address": "Noida",
    "country": "India"
}

# sort the dictionary by key - it will return list sorted keys
sorted_keys = sorted(student.items(), key=lambda kv: kv[1])
print(sorted_keys)

# create object of OrderedDict
od = OrderedDict()

# convert sorted_keys to dictionary
for k, v in sorted_keys:
  od[k] = v

print(dict(od))

Output

{'age': '21', 'course': 'BCA', 'country': 'India', 'address': 'Noida', 'roll_no': 'ST001', 'name': 'Vishvajit'}
Python Tutorials

Summary

So, IN this article we have seen all about How to sort Python Dictionary by key and value. Here we will demonstrate various ways to sort the dictionary in Python by key or value.
You can use any one of them as per your requirement. I hope, after leaving this article, you don’t have any confusion regarding how to sort Python Dictionary by key or value.

If you like this article, please share it and keep visiting for further Python tutorials.

Thanks for reading…

Ref:- Click Here

How to Convert JSON To Python Object
How to Convert Python Class Object to JSON

Related Posts