61

「深さ」キーで OrderedDict の OrderedDict をソートしようとしています。その 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)
  ])),
]) 

並べ替えられた辞書は次のようになります。

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)
  ])), 
]) 

それを取得する方法はありますか?

4

3 に答える 3

112

OrderedDictは広告掲載順で並べ替えられているため、新しいものを作成する必要があります。

あなたの場合、コードは次のようになります。

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

その他の例については、 http://docs.python.org/dev/library/collections.html#ordereddict-examples-and-recipesを参照してください。

.items()Python 3 の場合、 の代わりに使用する必要があることに注意してください.iteritems()

于 2011-11-07T00:09:16.703 に答える
20
>>> OrderedDict(sorted(od.items(), key=lambda item: item[1]['depth']))
于 2011-11-07T00:12:23.367 に答える
4

場合によっては、最初のディクショナリを保持し、新しいディクショナリを作成したくない場合があります。

その場合、次のことができます。

temp = sorted(list(foo.items()), key=lambda x: x[1]['depth'])
foo.clear()
foo.update(temp)
于 2018-04-05T05:47:19.883 に答える