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

标签 python sorting dictionary

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

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

最佳答案

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

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']))

关于Python 3 按值对字典列表进行排序,其中值以字符串开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41236551/

相关文章:

python - 获取按钮小部件的文本

python - 正则表达式在字符串开头未匹配

java - 自定义对象的ArrayList的排序是如何工作的?

python - 从字典中调用字典中的信息

python - 具有自定义比较谓词的 heapq

Python:更改来自函数参数的全局变量

python - Panda 的合并返回空,不明白为什么

Java:根据大小对 TreeSet 进行排序

php - 项目排名,使用 Reddit 排名算法按置信度排序

java - 两个 map 缩减作业并将每个作业的缩减值加入一个包含两个值的列表