How to sort OrderedDict of OrderedDict?

房东的猫 提交于 2019-11-26 08:36:46

问题


I\'m trying to sort OrderedDict in OrderedDict by \'depth\' key. Is there any solution to sort that Dictionary ?

OrderedDict([
  (2, OrderedDict([
    (\'depth\', 0),  
    (\'height\', 51), 
    (\'width\', 51),   
    (\'id\', 100)
  ])), 
  (1, OrderedDict([
    (\'depth\', 2),  
    (\'height\', 51), 
    (\'width\', 51),  
    (\'id\', 55)
  ])), 
  (0, OrderedDict([
    (\'depth\', 1),  
    (\'height\', 51), 
    (\'width\', 51),  
    (\'id\', 48)
  ])),
]) 

Sorted dict should look like this:

OrderedDict([
  (2, OrderedDict([
    (\'depth\', 0),  
    (\'height\', 51), 
    (\'width\', 51),   
    (\'id\', 100)
  ])), 
  (0, OrderedDict([
    (\'depth\', 1),  
    (\'height\', 51), 
    (\'width\', 51),  
    (\'id\', 48)
  ])),
  (1, OrderedDict([
    (\'depth\', 2),  
    (\'height\', 51), 
    (\'width\', 51),  
    (\'id\', 55)
  ])), 
]) 

Any idea how to get it?


回答1:


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().




回答2:


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



回答3:


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)


来源:https://stackoverflow.com/questions/8031418/how-to-sort-ordereddict-of-ordereddict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!