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:
CODE:
mydict = {'0d6f4012-16b4-4192-a854-fe9447b3f5cb':
{'CLAIMID': '123456789',
'CLAIMDATE': '20120508',
'AMOUNT': '365.64', 'EXPDATE': '20120831'},
'fe614868-d0c0-4c62-ae02-7737dea82dba':
{'CLAIMID': '45689654',
'CLAIMDATE': '20120508',
'AMOUNT': '185.55', 'EXPDATE': '20120831'},
'ca1aa579-a9e7-4ade-80a3-0de8af4bcb21':
{'CLAIMID': '98754651',
'CLAIMDATE': '20120508',
'AMOUNT': '93.00', 'EXPDATE': '20120831'},
'ccb8641f-c1bd-45be-8f5e-e39b3be2e0e3':
{'CLAIMID': '789464321',
'CLAIMDATE': '20120508', 'AMOUNT': '0.00',
'EXPDATE': ''},
'e1c445c2-5148-4a08-9b7e-ff5ed51c43ed':
{'CLAIMID': '897987945',
'CLAIMDATE': '20120508',
'AMOUNT': '62.66', 'EXPDATE': '20120831'},
'77ad6dd4-5704-4060-9c38-6a93721ef98e':
{'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:
CODE:
sorted_keys = sorted(mydict.keys(), key=lambda y: (mydict[y]['CLAIMID']))
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/301743/viewspace-733543/
,如需转载,请注明出处,否则将追究法律责任。