基于键重新排列嵌套字典内的字典

时间:2017-12-28 08:04:12

标签: python list 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'}]}]

我想按键Visitors按照下面的降序排序子词典In_Time

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'}]}]

我试图采用这种方法: from operator import itemgetter

但我无法获得所需的输出,有什么方法或建议可以帮助我吗?

感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

只需对子词典test[0]['Visitors'] = sorted(test[0]['Visitors'], key = lambda x: x['In_Time'], reverse = True) 进行排序并将其分配回来。

itemgetter

如果您想使用from operator import itemgetter test[0]['Visitors'] = sorted(test[0]['Visitors'], key=itemgetter('In_Time'), reverse=True)

[{'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'}]}]

输入:

[{'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'}]}]

输出:

android:permission="android.permission.BIND_JOB_SERVICE"