Home >Backend Development >Python Tutorial >How Can I Create a Sorted, Ordered Collection from a Python Dictionary?

How Can I Create a Sorted, Ordered Collection from a Python Dictionary?

Barbara Streisand
Barbara StreisandOriginal
2024-12-28 22:28:16767browse

How Can I Create a Sorted, Ordered Collection from a Python Dictionary?

Sorting a Dictionary by Key: Acquiring an Ordered Collection

The intrinsic nature of Python's dictionaries is unordered, barring the introduction of Python 3.7. While sorting the (key, value) pairs may appear as a solution, it's crucial to acknowledge that preserving the sorted order upon storing the elements back into a dictionary is not feasible.

To seamlessly establish an ordered collection based on key values, the utilization of the OrderedDict class prevails as the optimum approach. This class possesses the unique ability to retain the insertion sequence of its elements:

import collections

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

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

print(od)  # OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])

Although od's printed representation may vary, it will uphold the desired order during subsequent interactions:

print(od[1])  # 89
print(od[3])  # 0

for k, v in od.items():
    print(k, v)  # 1 89, 2 3, 3 0, 4 5

Considerations for Python 3 Users

Python 3 users should employ the .items() method instead of .iteritems() when iterating through the OrderedDict for maintaining compatibility:

for k, v in od.items():
    print(k, v)  # 1 89, 2 3, 3 0, 4 5

The above is the detailed content of How Can I Create a Sorted, Ordered Collection from a Python Dictionary?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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