python--字典排序,,字典排序是pytho


字典排序是python里比较常用的方法,在此作下总结。

按键排序

>>> test_dict 
{1: ‘a‘, 2: ‘b‘, 3: ‘c‘, 4: ‘d‘}>>> key_sort=sorted(test_dict.iteritems(), key=lambda key:key[0], reverse = False)>>> key_sort[(1, ‘a‘), (2, ‘b‘), (3, ‘c‘), (4, ‘d‘)]>>> key_sort=sorted(test_dict.iteritems(), key=lambda key:key[0], reverse = True)>>> key_sort[(4, ‘d‘), (3, ‘c‘), (2, ‘b‘), (1, ‘a‘)]>>> test_dict{1: ‘a‘, 2: ‘b‘, 3: ‘c‘, 4: ‘d‘}

按值排序

>>> value_sort=sorted(test_dict.iteritems(), key=lambda value:value[1], reverse = True)>>> value_sort[(4, ‘d‘), (3, ‘c‘), (2, ‘b‘), (1, ‘a‘)]

  

python--字典排序

评论关闭