首页 > Linux操作系统 > Linux操作系统 > Python算法-How to sort a dictionary by value

Python算法-How to sort a dictionary by value

原创 Linux操作系统 作者:jieforest 时间:2012-06-21 11:47:57 0 删除 编辑
The other day I was asked if there was a way to sort a dictionary by value. If you use Python regularly, then you know that the dictionary data structure is by definition an unsorted mapping type. Some would define a dict as a hash table. Regardless, I needed a way to sort a nested dictionary (i.e. a dictionary of dictionaries) based on a value in the nested dictionaries so I could iterate over the keys in the specified order. We’ll spend some time looking at an implementation I found.

After Googling for ideas, I came across an answer on StackOverflow that did most of what I wanted. I had to modify it slightly to make it sort using my nested dictionary values though, but that was surprisingly easy. Before we get to the answer, we should take a quick look at the data structure. Here is a variation of the beast minus the private parts that were removed for your safety:


mydict = {'0d6f4012-16b4-4192-a854-fe9447b3f5cb':
          {'CLAIMID': '123456789',
           'CLAIMDATE': '20120508',
           'AMOUNT': '365.64', 'EXPDATE': '20120831'},
          {'CLAIMID': '45689654',
           'CLAIMDATE': '20120508',
           'AMOUNT': '185.55', 'EXPDATE': '20120831'},
          {'CLAIMID': '98754651',
           'CLAIMDATE': '20120508',
           'AMOUNT': '93.00', 'EXPDATE': '20120831'},
          {'CLAIMID': '789464321',
           'CLAIMDATE': '20120508', 'AMOUNT': '0.00',
           'EXPDATE': ''},
          {'CLAIMID': '897987945',
           'CLAIMDATE': '20120508',
           'AMOUNT': '62.66', 'EXPDATE': '20120831'},
          {'CLAIMID': '23212315',
           'CLAIMDATE': '20120508',
           'AMOUNT': '41.05', 'EXPDATE': '20120831'}
          }Now we know what we’re dealing with. Let’s take a quick look at the slightly modified answer I came up with:


sorted_keys = sorted(mydict.keys(), key=lambda y: (mydict[y]['CLAIMID']))

来自 “ ITPUB博客 ” ,链接:,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录


  • 博文量
  • 访问量