KnowledgeBoat Logo

Computer Science

Can you change the order of dictionary's contents, i.e., can you sort the contents of a dictionary ?

Python Dictionaries

8 Likes

Answer

No, the contents of a dictionary cannot be sorted in place like that of a list. However, we can indirectly sort the keys and values of a dictionary by using sorted() function:

  • sorted(dictionary.keys())
  • sorted(dictionary.values())
  • sorted(dictionary)
  • sorted(dictionary.items())

For example:

>>> d = {"def" : 2 ,"abc" : 1, "mno" : 3}
>>> sorted(d.keys())
>>> sorted(d.values())
>>> sorted(d)
>>> sorted(d.items())
Output
['abc', 'def', 'mno']  
[1, 2, 3]  
['abc', 'def', 'mno']  
[('abc', 1), ('def', 2), ('mno', 3)]  

Answered By

2 Likes


Related Questions