首页 > 代码库 > sort a Python dictionary by value
sort a Python dictionary by value
首先要明确一点,Python的dict本身是不能被sort的,更明确地表达应该是“将一个dict通过操作转化为value有序的列表”
有以下几种方法:
1.
import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(1)) #sorted by value sorted_x = sorted(x.items(), key=operator.itemgetter(0)) #sorted by key
2.
sorted(dict1, key=dict1.get)
3.
sorted(d.items(), key=lambda x: x[1])
4.
sorted([(value,key) for (key,value) in mydict.items()])
5. Use OrderedDict
>>> # regular unsorted dictionary >>> d = {‘banana‘: 3, ‘apple‘: 4, ‘pear‘: 1, ‘orange‘: 2} >>> # dictionary sorted by key >>> OrderedDict(sorted(d.items(), key=lambda t: t[0])) OrderedDict([(‘apple‘, 4), (‘banana‘, 3), (‘orange‘, 2), (‘pear‘, 1)]) >>> # dictionary sorted by value >>> OrderedDict(sorted(d.items(), key=lambda t: t[1])) OrderedDict([(‘pear‘, 1), (‘orange‘, 2), (‘banana‘, 3), (‘apple‘, 4)]) >>> # dictionary sorted by length of the key string >>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0]))) OrderedDict([(‘pear‘, 1), (‘apple‘, 4), (‘orange‘, 2), (‘banana‘, 3)])
sort a Python dictionary by value
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。