How to sort OrderedDict of OrderedDict - Python

强颜欢笑 提交于 2019-11-27 02:13:55
ThiefMaster

You'll have to create a new one since OrderedDict is sorted by insertion order.

In your case the code would look like this:

foo = OrderedDict(sorted(foo.iteritems(), key=lambda x: x[1]['depth']))

See http://docs.python.org/dev/library/collections.html#ordereddict-examples-and-recipes for more examples.

Note for Python 3 you will need to use .items() instead of .iteritems().

>>> OrderedDict(sorted(od.items(), key=lambda item: item[1]['depth']))

Sometimes you might want to keep the initial dictionary and not create a new one.

In that case you could do the following:

temp = sorted(list(foo.items()), key=lambda x: x[1]['depth'])
foo.clear()
foo.update(temp)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!