我有一个嵌套字典(类别和子类别),dict
,我有排序困难。在Python中订购嵌套字典
的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'}}}
我如何排序这本字典,这样的“其他”子类别总是在嵌套字典的结尾出现了。例如,“艺术”类别的订单应该是:
..., u'arts': {u'painting': {'name': u'Painting', 'slug': u'painting'}, u'other-5': {'name': u'Other', 'slug': u'other-5'}}...
[OrderedDict](https://docs.python.org/2/library/collections.html#ordereddict-objects)可能对您有用 – Greg
是否有任何特殊原因需要订购类别? Python'dict'本质上是无序的,但有'OrderedDict'记住了键的添加顺序。 –