試圖找出如何按值排序字典列表,其中值以「自定義映射」列表中的字符串開頭。因此,例如,這裏的數據進行排序:Python 3按值排序字典列表,其中值以字符串開頭
'buckets': [
{
'doc_count': 23,
'key': 'Major League Stuff'
},
{
'doc_count': 23,
'key': 'Football Stuff'
},
{
'doc_count': 23,
'key': 'Football Stuff > Footballs'
},
{
'doc_count': 23,
'key': 'Football Stuff > Footballs > Pro'
},
{
'doc_count': 22,
'key': 'Football Stuff > Footballs > College'
},
{
'doc_count': 20,
'key': 'Football Stuff > Football Stuff Collections > Neat Stuff'
},
{
'doc_count': 19,
'key': 'Football Stuff > Helmets'
},
{
'doc_count': 4,
'key': 'Jewelry'
},
{
'doc_count': 4,
'key': 'Jewelry > Rings'
},
{
'doc_count': 2,
'key': 'All Gifts'
},
{
'doc_count': 2,
'key': 'Gifts for Her'
},
{
'doc_count': 2,
'key': 'Gifts for Her > Jewelry'
},
{
'doc_count': 2,
'key': 'Football Stuff > Footballs > Tykes'
},
{
'doc_count': 1,
'key': 'Brand new items'
},
{
'doc_count': 1,
'key': 'Jewelry > Rings and Bands'
}
{
'doc_count': 1,
'key': 'Football Stuff > Footballs > High School'
},
{
'doc_count': 1,
'key': 'Football Stuff > Pads'
}
]
,我希望它根據此列表進行排序:
sort_map = ['Football Stuff',
'Jewelry',
'Gifts for Her',
'Brand new items',
'Major League Stuff',
'All Gifts']
我有種想「startswith」可以工作,但我不當然如何
buckets = sorted(buckets, key=lambda x: sort_map.index(x['key'].startswith[?]))
任何幫助讚賞!
附註 - SO是要求我編輯,以解釋爲什麼這篇文章是不同於其他「排序字典值」職位。在發佈之前,我確實看過儘可能多的那些內容,而且沒有涉及匹配字符串部分的內容。所以我確實相信這不是重複的。
的可能的複製[排序按值Python字典(http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value) –
這不是和我解釋了爲什麼在OP – tarponjargon