基于嵌套键排序字典列表

时间:2017-01-15 06:29:20

标签: python django python-3.x sorting dictionary

[{'AvailableOffers': (d7b000a:Order {Amount:1000,Name:"000091",OfferedC:"JD",SeekingC:"Taobao",UserName:"xalima",ValidTill:"2019-11-30"}), 'Participants': 2, 'OrderID': ['000089', '000091', '000089']}
 {'AvailableOffers': (d7b000a:Order {Amount:1000,Name:"000091",OfferedC:"JD",SeekingC:"Taobao",UserName:"xalima",ValidTill:"2019-11-30"}), 'Participants': 2, 'OrderID': ['000089', '000091', '000089']}
 {'AvailableOffers': (b222004:Order {Amount:1000,Name:"000093",OfferedC:"JD",SeekingC:"China Airline",UserName:"yunis",ValidTill:"2017-11-11"}), 'Participants': 3, 'OrderID': ['000089', '000093', '000090', '000089']}
 {'AvailableOffers': (d7b000a:Order {Amount:1000,Name:"000091",OfferedC:"JD",SeekingC:"Taobao",UserName:"xalima",ValidTill:"2019-11-30"}), 'Participants': 5, 'OrderID': ['000089', '000091', '000096', '000095', '000090', '000089']}
 {'AvailableOffers': (d7b000a:Order {Amount:1000,Name:"000091",OfferedC:"JD",SeekingC:"Taobao",UserName:"xalima",ValidTill:"2019-11-30"}), 'Participants': 6, 'OrderID': ['000089', '000091', '000096', '000097', '000093', '000090', '000089']}]

这是我要排序的列表字典,我现在可以做的是排序

ListData_by_Participants = sorted(ListData, key=itemgetter("Participants"))

我想得到的帮助是

ListData_by_Validity = sorted(ListData,
                              key=itemgetter("AvailableOffers")("ValidTill")) 

有办法管理吗?

1 个答案:

答案 0 :(得分:1)

为了使用嵌套密钥对字典列表进行排序,您可以将 lambda表达式用作:

my_dict_list = [{'parent_key': {'my_key_1': 10, 'my_key_2': 2}},
                {'parent_key': {'my_key_1': 5, 'my_key_2': 4}},
                {'parent_key': {'my_key_1': 10, 'my_key_2': 6}},
                {'parent_key': {'my_key_1': 5, 'my_key_2': 2}},
                {'parent_key': {'my_key_1': 10, 'my_key_2': 3}},
]

sorted(my_dict_list, key=lambda x: (
        x['parent_key']['my_key_1'], x['parent_key']['my_key_2']))
#  value of first 'key' to sort-^                     ^
#               in case of same value for first 'key'-^   
#               sort based on second key -------------^

将排序列表返回为:

[{'parent_key': {'my_key_2': 2, 'my_key_1': 5}}, 
 {'parent_key': {'my_key_2': 4, 'my_key_1': 5}}, 
 {'parent_key': {'my_key_2': 2, 'my_key_1': 10}}, 
 {'parent_key': {'my_key_2': 3, 'my_key_1': 10}}, 
 {'parent_key': {'my_key_2': 6, 'my_key_1': 10}}]