CBSE Class 11 Computer Science Question 65 of 112

Dictionaries — Question 5

Back to all questions
5
Question

Question 5

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

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)]