How to sort a dictionary by value or key?
## # Python's program to sort a dictionary by value or key? import operator x = {'z': 10, 'l': 50, 'c': 74, 'm': 12, 'f': 44, 'g': 19} print(x) sorted_value = sorted(x.items(), key=operator.itemgetter(1)) print("\nSort By Value") print(sorted_value) sorted_key = sorted(x.items(), key=operator.itemgetter(0)) print("\nSort By Key") print(sorted_key)
Sample output of above program.
C:\programs\examples>pep8 --first example3.py
C:\programs\examples>python example3.py
{'z': 10, 'l': 50, 'g': 19, 'f': 44, 'm': 12, 'c': 74}
Sort By Value
[('z', 10), ('m', 12), ('g', 19), ('f', 44), ('l', 50), ('c', 74)]
Sort By Key
[('c', 74), ('f', 44), ('g', 19), ('l', 50), ('m', 12), ('z', 10)]
C:\programs\examples>
C:\programs\examples>python example3.py
{'z': 10, 'l': 50, 'g': 19, 'f': 44, 'm': 12, 'c': 74}
Sort By Value
[('z', 10), ('m', 12), ('g', 19), ('f', 44), ('l', 50), ('c', 74)]
Sort By Key
[('c', 74), ('f', 44), ('g', 19), ('l', 50), ('m', 12), ('z', 10)]
C:\programs\examples>
2018-04-05T17:50:14+05:30
2018-04-05T17:50:14+05:30
Amit Arora
Amit Arora
Python Programming Tutorial
Python
Practical Solution