How to sort a nested Python dictionary?
Answers
Tutorialspoint
Search your favorite tutorials...
How to sort a nested Python dictionary?
PythonProgramming
Can anyone explain the concept sort a nested Python dictionary clearly?
Follow Answer 573
1 Answer
karthikeya Boyini
Karthikeya Boyini
Answered on 18th Apr, 2018
If you have a dictionary of the following format:
{
'KEY1':{'name':'foo','data':1351,'completed':100},
'KEY2':{'name':'bar','data':1541,'completed':12},
'KEY3':{'name':'baz','data':58413,'completed':18}
}
And you want to sort by the key, completed within each entry, in a ascending order, you can use the sorted function with a lambda that specifies which key to use to sort the data. For example,
my_collection = {
'KEY1':{'name':'foo','data':1351,'completed':100},
'KEY2':{'name':'bar','data':1541,'completed':12},
'KEY3':{'name':'baz','data':58413,'completed':18}
}
sorted_keys = sorted(my_collection, key=lambda x: (my_collection[x]['completed']))
print(sorted_keys)
This will give the output:
['KEY2', 'KEY3', 'KEY1']