对嵌套字典进行排序,然后对外部字典进行排序

时间:2016-08-15 00:27:36

标签: python sorting dictionary

我有州和县的字典:

{
  'WI': {'CountyZ': 0, 
         'CountyC': 0, 
         'CountyD': 0},
  'IL': {'CountyM': 0, 
         'CountyW': 0, 
         'CountyA': 0}
}

我想根据键对各县的内部词典进行排序,然后根据键对外部词典进行排序。

我已尝试过以下操作,但我无法获得所需的结果:

sorted(sorted(states.items(), key=lambda x: x[0]), key=lambda y: y[1].items())

我想得到这样的东西:

[('IL', [('CountyA', 0), ('CountyM', 0), ('CountyW', 0)]), 
 ('WI', [('CountyC', 0), ('CountyD', 0), ('CountyZ', 0)])]

1 个答案:

答案 0 :(得分:1)

您可以像这样获取元组的排序列表:

d = {
  'WI': {'CountyZ': 0,
         'CountyC': 0,
         'CountyD': 0},
  'IL': {'CountyM': 0,
         'CountyW': 0,
         'CountyA': 0}
}

print sorted((key, sorted(inner_dict.items())) for key, inner_dict in d.iteritems())
相关问题