我有这本词典:
statuses = {
'pending' : {'status_for':'all', 'position':1},
'cancelled' : {'status_for':'all','position':2},
'approved' : {'status_for':'owner', 'position':1},
'rejected - owner' : {'status_for':'owner', 'position':2},
'accepted' : {'status_for':'dev', 'position':1},
'rejected - developer' : {'status_for':'dev', 'position':3},
'closed' : {'status_for':'dev', 'position':5},
}
我还有一个函数来提取status_for
或owner
的所有dev
值,看起来像这样并将它放入PyQt QComboBox:
for s in statuses:
if statuses[s]['status_for'] == "dev" or statuses[s]['status_for'] == "all":
cb_developer_status.addItem(s.capitalize(), s)
我想通过position
值来订购这些。有什么好办法可以做到这一点,所以当我使用组合框填充时,我会按照预定义的顺序使用它?
我意识到上面的代码片段正在检查'dev'和'all',我现在的假设是我必须循环遍历字典两次以按照我希望的顺序获得两个单独的块(即。'all'出现在'dev'之前。)
我看到this post,但我不确定如何将此答案转换为某些内容 是一本字典词典。
答案 0 :(得分:25)
这样的事情会起作用吗?与您关联的帖子类似,它使用key
sorted
函数提供自定义排序顺序。 iteritems()
返回(key, value)
元组,以便传递到lambda (x, y): y['position']
,其中y['position']
是值(您的嵌套字典,按状态键入),{{1} }是您要排序的项目。
position
答案 1 :(得分:9)
In [232]: statuses = {
'pending' : {'status_for':'all', 'position':1},
'cancelled' : {'status_for':'all','position':2},
'approved' : {'status_for':'owner', 'position':1},
'rejected - owner' : {'status_for':'owner', 'position':2},
'accepted' : {'status_for':'dev', 'position':1},
'rejected - developer' : {'status_for':'dev', 'position':3},
'closed' : {'status_for':'dev', 'position':5},
}
In [235]: sorted(statuses,key=lambda x:statuses[x]['position'])
Out[235]:
['accepted',
'approved',
'pending',
'rejected - owner',
'cancelled',
'rejected - developer',
'closed']
或使用operator.getitem()
:
In [260]: from operator import *
In [261]: sorted(statuses.items(),key=lambda x:getitem(x[1],'position'))
Out[261]:
[('accepted', {'position': 1, 'status_for': 'dev'}),
('approved', {'position': 1, 'status_for': 'owner'}),
('pending', {'position': 1, 'status_for': 'all'}),
('rejected - owner', {'position': 2, 'status_for': 'owner'}),
('cancelled', {'position': 2, 'status_for': 'all'}),
('rejected - developer', {'position': 3, 'status_for': 'dev'}),
('closed', {'position': 5, 'status_for': 'dev'})]