[Rod Stephens Books]
Index Books Python Examples About Rod Contact
[Mastodon] [Bluesky] [Facebook]
[Build Your Own Python Action Arcade!]

[Build Your Own Ray Tracer With Python]

[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

Title: Sort the keys and values in a dictionary in Python

[Dictionary items in natural order, sorted by key, and sorted by value in Python]

This example shows how you can list a dictionary's keys and values in sorted order.

A dictionary does not guarantee the ordering of the items it contains. Initially they are probably stored in the order in which you add them to the dictionary, but as you add and remove items, they may be rearranged arbitrarily.

Fortunately, it's pretty easy to list the items sorted. The following code creates a dictionary and the shows its contents in three orders.

dict = {1: 'Ant', 4: 'Cat', 2: 'Eagle', 3: 'Bear', } print('Natural order:') for k, v in dict.items(): print(f'{k}: {v}') print() print('Sorted by key:') for k, v in sorted(dict.items()): print(f'{k}: {v}') print() print('Sorted by value:') for k, v in sorted(dict.items(), key=lambda pair: pair[1]): print(f'{k}: {v}')

The first statement creates the dictionary.

The first loop uses the dictionary's items method to iterate through the dictionary's keys and values in whatever order they're in within the dictionary. Inside the loop, the program displays each key/value pair.

The second loop also uses items to get the dictionary's key/value pairs. This time is passes the result of items to the sorted function. The items method returns tuples holding the key/value pairs. When you pass a sequence of tuples to sorted like this, it sorts them by the first items in the tuples. In this case, that means sorted sorts the pairs by the dictionary keys so the list appears in key order.

The third loop is similar to the second except it passes a lambda function into sorted to make it use each tuple's second item as the key so the tuples are sorted by their values.

Conclusion

The items in a dictionary might be stored in the order in which you put them in the dictionary, but you should never count on that. If you care about the items' order, you should explicitly sort them.

This example prints the items in various orders. Alternatively, you could save the result of sorted in a list or other collection object. You could pass the result into dict to save the reordered items in a new dictionary, but you shouldn't rely on the new dictionary maintaining the items' order so why bother?

Download the example to experiment with it.

© 2025 Rocky Mountain Computer Consulting, Inc. All rights reserved.