Python3按值对字典列表进行排序,其中值以字符串开头

Python3按值对字典列表进行排序,其中值以字符串开头,python,sorting,dictionary,Python,Sorting,Dictionary,试图找出如何按值对字典列表进行排序,其中值以“自定义映射”列表中的字符串开头。例如,下面是要排序的数据: 'buckets': [ { 'doc_count': 23, 'key': 'Major League Stuff' }, { 'doc_count': 23, 'key': 'Football Stuff' }, { 'doc_count': 23, '

试图找出如何按值对字典列表进行排序,其中值以“自定义映射”列表中的字符串开头。例如,下面是要排序的数据:

'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[?]))
感谢您的帮助


旁注-所以我要求编辑来解释为什么这篇文章不同于其他“按值排序”的文章。在发布这篇文章之前,我确实查看了尽可能多的内容,并且没有任何内容涉及字符串的匹配部分。所以我相信这不是重复的。

我会利用这样一个事实,即您可以根据
“>”
进行拆分,并获取第一个字段的索引

buckets = sorted(buckets, key=lambda x: sort_map.index(x['key'].split(" > ")[0]))
为了提供第二个alpha标准,您可以返回一个元组,其中包含完整字符串作为第二项,以便在索引相同的情况下按字母顺序排序:

buckets = sorted(buckets, key=lambda x: (sort_map.index(x['key'].split(" > ")[0]),x['key']))

我认为最好创建一个单独的函数,而不是
lambda
,因为它使代码更容易理解

def get_index(x):
    for i, e in enumerate(sort_map):
        if x['key'].startswith(e):
            return i

buckets = sorted(buckets, key=get_index)

可能的副本不是,我在OPyes的结尾解释了为什么在更短和更可读之间做出艰难的选择。谢谢你的解决方案。