按价值排序字典字典 [英] Sort dictionary of dictionaries by value
问题描述
我有这个字典:
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
的价值是所有者
或 dev
这个并把它放入一个PyQt QComboBox:
I've also got a function to pull all status_for
values of either owner
or dev
that looks like this and put it into a 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)
我想通过位置
订单。这是一个很好的方法,所以当我使用组合框填充我有预定义的顺序?
I'd like to order these by the position
value though. What is a good way to do this, so that when I populate by combobox I have it in a predefined order?
我意识到,上面的代码片段是检查' dev'和'all',我现在的想法是,我必须循环通过字典两次,以我想要的顺序获取两个单独的块(即'all'出现在'dev'之前)。
I realize that the snippet above is checking for both 'dev' and 'all', my assumption right now is that I'd have to loop through the dictionary twice to get the two separate blocks in the order I wish (ie. 'all' appears before 'dev').
我看到这篇文章 ,但我不知道如何将这个答案转换成
是字典的字典。
I saw this post, but I'm not sure how to convert this answer to something that is a dictionary of dictionaries.
推荐答案
这样的事情能起作用吗?与您链接的帖子类似,它使用 c> c> c> c>
iteritems()
返回一个(key,value)
元组,以便被传入 lambda (x,y):y ['position']
,其中 y ['position']
是值(你的嵌套字典,由状态)和位置
是要排序的项目。
Would something like this work? Similar to the post you linked, this uses the key
function of sorted
to provide a custom sort order. iteritems()
returns a (key, value)
tuple, so that gets passed into lambda (x, y): y['position']
, where y['position']
is the value (your nested dictionary, keyed by the status), and position
is the item by which you want to sort.
In [35]: 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 [44]: for s in sorted(statuses.iteritems(), key=lambda (x, y): y['position']):
....: print s
....:
....:
('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'})
这篇关于按价值排序字典字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!