print sorted(dict1.items(), key=lambda d: d[0]) # 按照value进行排序 print sorted(dict1.items(), key=lambda d: d[1]) 下面给出python内置sorted函数的帮助文档: sorted(...) sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list 看了上面这么多种对dictionary排序的方法...
print sorted(dict1.items(), key=lambda d: d[1]) 3 扩展用法:Key Function 从Python2.4开始,list.sort() 和 sorted() 都增加了一个 ‘key’ 参数用来在进行比较之前指定每个列表元素上要调用的函数。 例1: 不区分大小写的字符串比较排序: >>> sorted("This is a test string from Andrew".split()...
sorted_tuples = sorted(dictionary.items(), key=lambda x: (x[1], x[0])) # 返回排序后的字典 return dict(sorted_tuples) # 示例字典 my_dict = {'a': 3, 'b': 2, 'c': 3, 'd': 1} # 按值排序,在值相等的情况下按键排序 sorted_dict = sort_dict_by_value_then_key(my_dict) ...
'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),('oran...
dictionary本身没有顺序概念,但是总是在某些时候,但是我们常常需要对字典进行排序 方法1:按照key值排序。 def sortedDictValues1(adict): items = adict.items() print "items:",items items.sort() return [value for key, value in items] adict = {"a1":11,"b1":2,"c1":30,"e1":20,"d1":4}...
1 按照Key值排序 #最简单的方法,这个是按照key值排序: def sortedDictValues1(adict): items = adict.items() items.sort() return [value for key, value in items] #又一个按照key值排序,貌似比上一个速度要快点 def sortedDictValues2(adict): keys = adict.keys() keys.sort() return [dict[...
d_sorted_by_value = sorted(d.items(), key=lambda x: x[1]) # 根据字典值的升序排序 d_sorted_by_key [('a', 2), ('b', 1), ('c', 10)] d_sorted_by_value [('b', 1), ('a', 2), ('c', 10)] 当然,因为字典本身是无序的,所以这里返回了一个列表。列表中的每个元素,是由...
Sorting by values requires specifying a sort key using a lambda function or itemgetter().By the end of this tutorial, you’ll understand that:You can sort a dictionary by its keys using sorted() with .items() and dict(). To sort by values, you use sorted() with a key function like...
Sort a Python dictionary by key Code: color_dict = {'red':'#FF0000', 'green':'#008000', 'black':'#000000', 'white':'#FFFFFF'} for key in sorted(color_dict): print("%s: %s" % (key, color_dict[key])) Output: >>>
import operator d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} print('Original dictionary : ',d) sorted_d = dict(sorted(d.items(), key=operator.itemgetter(1))) print('Dictionary in ascending order by value : ',sorted_d) sorted_d = dict( sorted(d.items(), key=operator.itemgetter...