tar*_*gon 3 python sorting dictionary
试图弄清楚如何按值对字典列表进行排序,其中值以"自定义地图"列表中的字符串开头.例如,这里是要排序的数据:
'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'
}
]
Run Code Online (Sandbox Code Playgroud)
我想根据这个列表对它进行排序:
sort_map = ['Football Stuff',
'Jewelry',
'Gifts for Her',
'Brand new items',
'Major League Stuff',
'All Gifts']
Run Code Online (Sandbox Code Playgroud)
我有点想"startwith"可以工作,但我不确定如何
buckets = sorted(buckets, key=lambda x: sort_map.index(x['key'].startswith[?]))
Run Code Online (Sandbox Code Playgroud)
任何帮助赞赏!
旁注 - SO要求我编辑解释为什么这篇文章与其他"按价值排序"字样不同.在发布此内容之前,我确实查看了很多这样的内容,并且没有涉及匹配字符串部分的内容.所以我相信这不是重复的.
我会利用这样一个事实,你可以根据" > "并拆分第一个字段的索引
buckets = sorted(buckets, key=lambda x: sort_map.index(x['key'].split(" > ")[0]))
Run Code Online (Sandbox Code Playgroud)
要提供第二个alpha标准,您可以返回一个元组作为第二个项目的完整字符串,以便在相同索引的情况下按字母顺序排序:
buckets = sorted(buckets, key=lambda x: (sort_map.index(x['key'].split(" > ")[0]),x['key']))
Run Code Online (Sandbox Code Playgroud)