我有一本看起来像这样的字典
{'Africa': {'Name': 'Africa',
'men': 33333,
'priority': 3,
'women': 30000},
'America': {'Name': 'USA',
'men': 1114444411333L,
'priority': 4,
'women': 44430000},
'Asia': {'Name': 'China',
'men': 444433333,
'priority': 2,
'women': 444430000},
'Europe': {'Name': 'UK',
'men': 11111333,
'priority': 1,
'women': 1111430000}}
我需要按Key = Priority
对此词典进行排序我正在使用2.7并尝试了一些选项(看起来不太优雅)。有什么建议吗?
答案 0 :(得分:8)
>>> d = {"Africa" :
{ "Name" : "Africa", "men": 33333, "women" : 30000, "priority" :3},
"Asia":
{ "Name" : "China", "men": 444433333, "women" : 444430000, "priority" :2},
"Europe":
{ "Name" : "UK", "men": 11111333, "women" : 1111430000, "priority" :1},
"America":
{ "Name" : "USA", "men": 1114444411333, "women" : 44430000, "priority" :4}
}
>>> from collections import OrderedDict
>>> OrderedDict(sorted(d.items(), key=lambda x: x[1]['priority']))
OrderedDict([('Europe', {'priority': 1, 'men': 11111333, 'Name': 'UK', 'women': 1111430000}), ('Asia', {'priority': 2, 'men': 444433333, 'Name': 'China', 'women': 444430000}), ('Africa', {'priority': 3, 'men': 33333, 'Name': 'Africa', 'women': 30000}), ('America', {'priority': 4, 'men': 1114444411333L, 'Name': 'USA', 'women': 44430000})])
答案 1 :(得分:0)
无法对dict进行排序。您无法将字典排序为已排序,但您可以将其转换为已排序的元组列表。这是另一个排序版本;
data={'Africa': {'Name': 'Africa',
'men': 33333,
'priority': 3,
'women': 30000},
'America': {'Name': 'USA',
'men': 1114444411333L,
'priority': 4,
'women': 44430000},
'Asia': {'Name': 'China',
'men': 444433333,
'priority': 2,
'women': 444430000},
'Europe': {'Name': 'UK',
'men': 11111333,
'priority': 1,
'women': 1111430000}}
from operator import itemgetter
listOfTuple = sorted(data.items(), key= lambda(k,v):itemgetter(1)('priority'))
listOfTuple.sort(key=lambda tup:tup[1]['priority'])
print listOfTuple
>>>[('Europe', {'priority': 1, 'men': 11111333, 'Name': 'UK', 'women': 1111430000}), ('Asia', {'priority': 2, 'men': 444433333, 'Name': 'China', 'women': 444430000}), ('Africa', {'priority': 3, 'men': 33333, 'Name': 'Africa', 'women': 30000}), ('America', {'priority': 4, 'men': 1114444411333L, 'Name': 'USA', 'women': 44430000})]