[英]Sort nested dictionaries then sort outer 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)])]
您可以像這樣獲取元組的排序列表:
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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.