fork(1) download
  1.  
  2. import operator
  3.  
  4. x = {'Delhi': ['capital', 'state'],
  5. 'Uttar Pradesh': "population",
  6. 'Tamil Nadu': ['southern'],
  7. 'Assam': ['mountains']}
  8.  
  9. # To sort dict based on values
  10. sorted_x = sorted(x.items(), key=operator.itemgetter(1))
  11. print(sorted_x)
  12.  
  13. # To sort dict based on KEYS
  14. sorted_x = sorted(x.items(), key=operator.itemgetter(0))
  15. print(sorted_x)
  16.  
  17. # To sort dict based on KEYS
  18. sorted_x = sorted(x.items(), key=lambda x: x[0])
  19. print(sorted_x)
  20.  
  21. # To sort dict based on VALUES
  22. sorted_x = sorted(x.items(), key=lambda x: x[1])
  23. print(sorted_x)
Success #stdin #stdout 0.01s 9024KB
stdin
Standard input is empty
stdout
[('Delhi', ['capital', 'state']), ('Assam', ['mountains']), ('Tamil Nadu', ['southern']), ('Uttar Pradesh', 'population')]
[('Assam', ['mountains']), ('Delhi', ['capital', 'state']), ('Tamil Nadu', ['southern']), ('Uttar Pradesh', 'population')]
[('Assam', ['mountains']), ('Delhi', ['capital', 'state']), ('Tamil Nadu', ['southern']), ('Uttar Pradesh', 'population')]
[('Delhi', ['capital', 'state']), ('Assam', ['mountains']), ('Tamil Nadu', ['southern']), ('Uttar Pradesh', 'population')]