2

我有一本看起来像这样的字典

{'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 并尝试了几个选项(看起来不太优雅)。有什么建议么?

4

2 回答 2

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})])
于 2013-05-02T10:47:31.827 回答
0

无法对字典进行排序。您无法获得已排序的字典,但您可以将其转换为已排序的元组列表。这是排序它的另一个版本;

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})]
于 2013-05-02T11:15:56.330 回答