在python中排序嵌套字典

2024-05-13 01:27:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个嵌套字典(category和subcategories),dict,排序有困难。你知道吗

dict的输出是:

{u'sports': {u'basketball': {'name': u'Basketball', 'slug': u'basketball'}, u'baseball': {'name': u'Baseball', 'slug': u'baseball'}}, u'dance': {u'salsa': {'name': u'Salsa', 'slug': u'salsa'}}, u'arts': {u'other-5': {'name': u'Other', 'slug': u'other-5'}, u'painting': {'name': u'Painting', 'slug': u'painting'}}, u'music': {u'cello': {'name': u'Cello', 'slug': u'cello'}, u'accordion': {'name': u'Accordion', 'slug': u'accordion'}}}

如何对该词典进行排序,使“other”子类别始终显示在嵌套词典的末尾。例如,“艺术”类别的顺序应为:

..., u'arts': {u'painting': {'name': u'Painting', 'slug': u'painting'}, u'other-5': {'name': u'Other', 'slug': u'other-5'}}...

Tags: name排序dict词典otherslugaccordionsalsa
2条回答

你对字典有一些重大的概念误解。python中的字典就像hash table,哈希表没有顺序。dict的输出实际上是依赖于环境的,所以不能依赖于环境。您可能会看到输出的一种方式,而其他人会看到另一种方式。您应该考虑改用^{}。你知道吗

Python字典(常规dict实例)没有排序。如果您想对dict进行排序,您可以:

from collections import OrderedDict

mynewdict = OrderedDict(sorted(yourdict.items()))

OrderedDict不提供排序机制,只考虑插入到它上面的键的顺序(我们对那些调用sorted的键进行排序)。你知道吗

因为您需要一个特定的条件(假设您的键是按字母顺序排列的,除了最后的“其他”键),所以您需要声明它:

def mycustomsort(key):
    return (0 if key != 'other' else 1, key)
mynewdict = OrderedDict(sorted(yourdict.items(), key=mycustomsort))

这样就为嵌套的条件创建了一个元组:第一个条件是other而不是no other,因此0或1(因为1更大,所以other更晚),而第二个条件是键本身。如果需要,可以删除第二个条件而不返回元组,但只能返回0和1,代码将不按字母顺序排序。你知道吗

如果您计划以后编辑词典,并且没有标准类支持,则此解决方案将不起作用。你知道吗

相关问题 更多 >