【问题标题】:Sort a dictionary based on alphanumeric keys根据字母数字键对字典进行排序
【发布时间】:2018-03-29 18:27:53
【问题描述】:

我有一个包含字母数字键的字典,我需要根据键的数值的递增顺序对它们进行排序。下面是我的字典

output_filters = {"filter22": "red", "filter13": "green", "filter36": "yellow"}

我希望最终字典的排序如下所示

output_filters = {"filter13": "green", "filter22": "red", "filter36": "yellow"}

现在我知道有类似的 stackoverflow 问题,但我无法适应我的情况。

这是我到目前为止所做的,但它不起作用

def key_func(s):
    return [int(x) if x.isdigit() else x for x in re.findall(r'\D+|\d+', s)]

sorted_keys = sorted(output_filters, key=key_func)

它给出不准确的结果。如何做到这一点?

【问题讨论】:

    标签: python-3.x sorting dictionary


    【解决方案1】:

    以下将为您提供排序后的List 键。

    x = [k for k, v in output_filters.items()]
    
    x = sorted(x, key=lambda x: int(x[6:])) # this will remove "filter" prefix
    
    # ['filter13', 'filter22', 'filter36']
    

    但是,您不能对字典进行排序。它们是无序的。如果确实需要排序,则需要使用OrderedDict

    https://docs.python.org/2/library/collections.html#collections.OrderedDict

    【讨论】:

    • 这不会根据filter 中的数值对键进行排序。如果x 包含密钥filter113 怎么办?
    • @AlanSTACK 嘿,我需要根据键对字典进行排序,并且已在某些 stackoverflow 帖子中完成。我只需要根据我的情况进行调整。
    • @SouvikRay 您是否考虑过从字典中取出键,对它们进行排序,然后遍历键并以这种方式访问​​字典?
    • @Wondercricket 有什么想法吗?
    • @SouvikRay x = sorted(x, key=lambda x: int(x[6:]))
    猜你喜欢
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 2011-02-11
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    相关资源
    最近更新 更多