Pages

Apr 22, 2015

[Python] A simple way to sort a dictionary

>>> 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)]
view raw sortDict.py hosted with ❤ by GitHub

No comments:

Post a Comment