This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> import operator | |
>>> x #x is a dictionary | |
{'cde': 456, 'abc': 789, 'efg': 123} | |
# only return keys | |
>>> sorted(x) | |
['abc', 'cde', 'efg'] | |
# sort by key, "reverse=True" means from large to small | |
>>> sorted(x.items(), key=operator.itemgetter(0), reverse=True) | |
[('efg', 123), ('cde', 456), ('abc', 789)] | |
# sort by value, just change the parameter in the itemgetter() | |
>>> sorted(x.items(), key=operator.itemgetter(1), reverse=True) | |
[('abc', 789), ('cde', 456), ('efg', 123)] |
No comments:
Post a Comment