Reputation: 6079
I have the below list of dictionary:
test = [{'Date': datetime.datetime(2017, 12, 26, 0, 0),'Visitors': [{u'Owner_Name': u'Ashish Bainade', u'Unit_ID': u'1000', u'ID': u'Ashish ainade 119', u'In_Time': datetime.datetime(2017, 12, 26, 12, 13), u'Wing': u'Z'},{u'Owner_Name': u'Ashish Bainade', u'Unit_ID': u'102', u'ID': u'6976', u'In_Time': datetime.datetime(2017, 12, 26, 13, 15), u'Wing': u'B'}]}]
I want to order the sub-dictionary Visitors
by key In_Time
in descending order like below
test = [{'Date': datetime.datetime(2017, 12, 26, 0, 0),'Visitors': [{u'Owner_Name': u'Ashish Bainade', u'Unit_ID': u'102', u'ID': u'6976', u'In_Time': datetime.datetime(2017, 12, 26, 13, 15), u'Wing': u'B'},{u'Owner_Name': u'Ashish Bainade', u'Unit_ID': u'1000', u'ID': u'Ashish ainade 119', u'In_Time': datetime.datetime(2017, 12, 26, 12, 13), u'Wing': u'Z'}]}]
I am trying to go down this approach :
from operator import itemgetter
But I am Unable to get the desired output , is there any way or suggestion that can help me ?
Any Help is appreciated.
Upvotes: 0
Views: 71
Reputation: 5109
Just sort the sub-dictionary Visitors
and assign it back.
test[0]['Visitors'] = sorted(test[0]['Visitors'], key = lambda x: x['In_Time'], reverse = True)
If you want to use itemgetter
:
from operator import itemgetter
test[0]['Visitors'] = sorted(test[0]['Visitors'], key=itemgetter('In_Time'), reverse=True)
Input:
[{'Date': datetime.datetime(2017, 12, 26, 0, 0),
'Visitors': [{u'ID': u'Ashish ainade 119',
u'In_Time': datetime.datetime(2017, 12, 26, 12, 13),
u'Owner_Name': u'Ashish Bainade',
u'Unit_ID': u'1000',
u'Wing': u'Z'},
{u'ID': u'6976',
u'In_Time': datetime.datetime(2017, 12, 26, 13, 15),
u'Owner_Name': u'Ashish Bainade',
u'Unit_ID': u'102',
u'Wing': u'B'}]}]
Output:
[{'Date': datetime.datetime(2017, 12, 26, 0, 0),
'Visitors': [{u'ID': u'6976',
u'In_Time': datetime.datetime(2017, 12, 26, 13, 15),
u'Owner_Name': u'Ashish Bainade',
u'Unit_ID': u'102',
u'Wing': u'B'},
{u'ID': u'Ashish ainade 119',
u'In_Time': datetime.datetime(2017, 12, 26, 12, 13),
u'Owner_Name': u'Ashish Bainade',
u'Unit_ID': u'1000',
u'Wing': u'Z'}]}]
Upvotes: 3