Home > Backend Development > Python Tutorial > How to Sort a Python Dictionary by Keys?

How to Sort a Python Dictionary by Keys?

Susan Sarandon
Release: 2024-12-23 19:09:15
Original
727 people have browsed it

How to Sort a Python Dictionary by Keys?

How to Sort a Dictionary using Python

Dictionaries in Python are unordered data structures. However, there are instances where sorting a dictionary by its keys is necessary.

Example Input:

{2:3, 1:89, 4:5, 3:0}
Copy after login

Desired Output:

{1:89, 2:3, 3:0, 4:5}
Copy after login

Standard Python Dictionaries

Standard Python dictionaries maintain key order only as of Python version 3.7. Prior to version 3.7, using the sorted(d.items()) function will not achieve the desired result as these dictionaries do not preserve the order of the sorted pairs.

OrderedDict

For versions prior to Python 3.7, the solution is to use the OrderedDict class from the collections module. This class stores key-value pairs in the order in which they are inserted, ensuring a consistent ordering.

import collections

d = {2:3, 1:89, 4:5, 3:0}

# Create an OrderedDict from sorted key-value pairs
od = collections.OrderedDict(sorted(d.items()))

print(od)
Copy after login

Output:

OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
Copy after login

Python 3

For Python versions 3 and above, the .items() method should be used instead of .iteritems():

for k, v in od.items():
    print(k, v)
Copy after login

Output:

1 89
2 3
3 0
4 5
Copy after login

The above is the detailed content of How to Sort a Python Dictionary by Keys?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template