

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to sort a dictionary in Python by keys?
Standard distribution of Python contains collections module. It has definitions of high performance container data types. OrderedDict is a sub class of dictionary which remembers the order of entries added in dictionary object. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.
>>> from collections import OrderedDict >>> D = {5:'fff', 3:'ttt', 1:'ooo',4:'bbb', 2:'ddd'} >>> OrderedDict(D.items()) OrderedDict([(5, 'fff'), (3, 'ttt'), (1, 'ooo'), (4, 'bbb'), (2, 'ddd')])
We also need to use sorted() function that sorts elements in an iterable in a specified order. The function takes a function as argument which is used as key for sorting. Since we intend to sort dictionary on keys, we take 0th element of tuple as key for sorting
>>> D = {5:'fff', 3:'ttt', 1:'ooo',4:'bbb', 2:'ddd'} >>> OrderedDict(sorted(D.items(), key = lambda t: t[0])) OrderedDict([(1, 'ooo'), (2, 'ddd'), (3, 'ttt'), (4, 'bbb'), (5, 'fff')])
The OrderedDict object can be parsed into a regular dictionary object
>>> D1 = dict(OrderedDict(sorted(D.items(), key = lambda t: t[0]))) >>> D1 {1: 'ooo', 2: 'ddd', 3: 'ttt', 4: 'bbb', 5: 'fff'}
- Related Questions & Answers
- How to sort a Python dictionary by value?
- How to sort a Python dictionary by datatype?
- How to sort a dictionary in Python by values?
- How to sort a dictionary in Python?
- How to add new keys to a dictionary in Python?
- How to sort a nested Python dictionary?
- Java Program to Sort map by keys
- How to create Python dictionary with duplicate keys?
- How does Python dictionary keys() Method work?
- Properties of Dictionary Keys in Python
- How to print all the keys of a dictionary in Python?
- How to convert Python dictionary keys/values to lowercase?
- Get dictionary keys as a list in Python
- How to insert new keys/values into Python dictionary?
- Python Extract specific keys from dictionary?
Advertisements