Skip to content

Instantly share code, notes, and snippets.

@kunpengku
Created July 31, 2017 07:40
Show Gist options
  • Save kunpengku/dd8f1c8cfeec722b31e0e9a1beecae87 to your computer and use it in GitHub Desktop.
Save kunpengku/dd8f1c8cfeec722b31e0e9a1beecae87 to your computer and use it in GitHub Desktop.
#coding:utf8
from collections import OrderedDict
d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
for k,v in d.items():
print(k,v)
print('按照 key 排序')
d2 = OrderedDict(sorted(d.items(), key=lambda t: t[0]))
for k,v in d2.items():
print(k,v)
print('按照 value 排序')
d3 = OrderedDict(sorted(d.items(), key=lambda t: t[1]))
for k,v in d3.items():
print(k,v)
#ref https://docs.python.org/2/library/collections.html#collections.OrderedDict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment