根据字典中值的大小对字典中的项排序

方法一:

def dict_sort():
    adict  = {'b':2,'a':1,'d':-3}
    items = adict.items()
    print items  # [('a', 1), ('b', 2), ('d', -3)]
    print sorted(items) # [('a', 1), ('b', 2), ('d', -3)],默认是按照第一项排序的
    print sorted(items,key=lambda x:x[1]) # [('d', -3), ('a', 1), ('b', 2)],可以指定第二项排序

方法二:


'''
根据字典中值的大小对字典中的项排序2-4imooc
'''
def sortedDictValues1():
   adict  = {'b':2,'a':1}
   items = adict.items()
   items.sort()
   return [value for key, value in items]

# sortedDictValues1()

def sortedDictValues2(adict):
   adict  = {'b':2,'a':1}
   keys = adict.keys()
   keys.sort()
   return [adict[key] for key in keys]

def out1():
   dict1 = {'b':2,'a':1}
   print sortedDictValues1(dict1)   # [1, 2]
   print sorted(dict1.items(), key=lambda d: d[0])   #[('a', 1), ('b', 2)]
   print sorted(dict1.items(), key = itemgetter(0))  # [('a', 1), ('b', 2)]

# out1()

# 字典按顺序输出
def dict_sorted3():
   dict1 = {'b':2,'a':1}
   keys = sorted(dict1.keys())
   dict2 = {}
   for i in keys:
       dict2.update({i:dict1[i]})
   print dict2
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容