字典,列表排序¶
字典¶
按key排序¶
items = dict.items()
items.sort()
for key,value in items:
print(key, value) # print(key,dict[key])
- print(key, dict[key] for key in sorted(dict.keys()))
按照value排序¶
- 把dictionary中的元素分离出来放到一个list中,对list排序,从而间接实现对dictionary的排序。这个“元素”可以是key,value或者item。
- 用lambda表达式来排序,更灵活
sorted(dict.items(), lambda x, y: cmp(x[1], y[1]))
#降序
sorted(dict.items(), lambda x, y: cmp(x[1], y[1]), reverse=True)