Skip to main content
 首页 » 编程设计

python之按 Python 中其他字典的值对字典进行排序

2025年05月04日16sky-heaven

如何在 Python 中通过 'votes' 对这个字典进行排序?

{ 
  1 : { 
    'votes' : 2, 
    'id' : 10 
  }, 
  2 : { 
    'votes' : 10, 
    'id' : 12 
  }, 
  3 : { 
    'votes' : 98, 
    'id' : 14 
  } 
} 

结果:

{ 
  3 : { 
    'votes' : 98, 
    'id' : 14 
  }, 
  2 : { 
    'votes' : 10, 
    'id' : 12 
  }, 
  1 : { 
    'votes' : 2, 
    'id' : 10 
  } 
} 

请您参考如下方法:

你可以使用 OrderedDict :

>>> from collections import OrderedDict 
>>> od = OrderedDict(sorted(d.items(), 
                     key=lambda t: t[1]['votes'], 
                     reverse=True)) 
>>> od 
OrderedDict([(3, {'votes': 98, 'id': 14}), 
             (2, {'votes': 10, 'id': 12}), 
             (1, {'votes': 2, 'id': 10})]) 

其中 d 是您的原始字典。