Python|按键排序嵌套字典
排序有非常生动的应用,有时我们可能会遇到需要通过嵌套键对嵌套字典进行排序的问题。这种类型的应用程序在 Web 开发中很流行,因为 JSON 格式非常流行。让我们讨论可以执行此操作的某些方式。
方法#1:使用OrderedDict() + sorted()
可以使用 OrderedDict函数执行此任务,该函数将字典转换为特定顺序,如其参数中提到的,由其中的 sorted函数操作,以按传递的键值排序。
# Python3 code to demonstrate
# Sort nested dictionary by key
# using OrderedDict() + sorted()
from collections import OrderedDict
from operator import getitem
# initializing dictionary
test_dict = {'Nikhil' : { 'roll' : 24, 'marks' : 17},
'Akshat' : {'roll' : 54, 'marks' : 12},
'Akash' : { 'roll' : 12, 'marks' : 15}}
# printing original dict
print("The original dictionary : " + str(test_dict))
# using OrderedDict() + sorted()
# Sort nested dictionary by key
res = OrderedDict(sorted(test_dict.items(),
key = lambda x: getitem(x[1], 'marks')))
# print result
print("The sorted dictionary by marks is : " + str(res))
The original dictionary : {‘Nikhil’: {‘roll’: 24, ‘marks’: 17}, ‘Akash’: {‘roll’: 12, ‘marks’: 15}, ‘Akshat’: {‘roll’: 54, ‘marks’: 12}}
The sorted dictionary by marks is : OrderedDict([(‘Akshat’, {‘roll’: 54, ‘marks’: 12}), (‘Akash’, {‘roll’: 12, ‘marks’: 15}), (‘Nikhil’, {‘roll’: 24, ‘marks’: 17})])
方法 #2:使用sorted()
如果我们只使用 sorted函数,我们可以更好地实现上述结果,因为它以更可用的格式返回结果,dict 并完全执行所需的任务。
# Python3 code to demonstrate
# Sort nested dictionary by key
# using sorted()
# initializing dictionary
test_dict = {'Nikhil' : { 'roll' : 24, 'marks' : 17},
'Akshat' : {'roll' : 54, 'marks' : 12},
'Akash' : { 'roll' : 12, 'marks' : 15}}
# printing original dict
print("The original dictionary : " + str(test_dict))
# using sorted()
# Sort nested dictionary by key
res = sorted(test_dict.items(), key = lambda x: x[1]['marks'])
# print result
print("The sorted dictionary by marks is : " + str(res))
The original dictionary : {‘Nikhil’: {‘marks’: 17, ‘roll’: 24}, ‘Akshat’: {‘marks’: 12, ‘roll’: 54}, ‘Akash’: {‘marks’: 15, ‘roll’: 12}}
The sorted dictionary by marks is : [(‘Akshat’, {‘marks’: 12, ‘roll’: 54}), (‘Akash’, {‘marks’: 15, ‘roll’: 12}), (‘Nikhil’, {‘marks’: 17, ‘roll’: 24})]