如何对包含多个词典的集合进行排序

时间:2018-04-10 12:28:13

标签: python-3.x list sorting dictionary

a_list=[
    {'status':'f','name':'battery','time':1.3},
    {'status':'a','name':'mouse','time':3.5},
    {'status':'p','name':'battery','time':1.0},
    {'status':'p','name':'battery','time':0.8},
    {'status':'n','name':'touch','time':1.6},
    {'status':'t','name':'typec','time':1.7},
    {'status':'fail','name':'keyboard','time':3.4},
    {'status':'fail','name':'keyboard','time':1.7},
    {'status':'fa','name':'mouse','time':1.8},
    {'status':'k','name':'touch','time':2.4}]

我想得到的结果是:我想在字典中放入相同的名称。然后根据时间排序。 结果如下:

sorted=[
  {'status':'f','name':'battery','time':0.8},{'status':'f','name':'battery','time':1.0},
  {'status':'p','name':'battery','time':1.3},{'status':'n','name':'touch','time':1.6,
  {'status':'k','name':'touch','time':2.4},{'status':'fail','name':'keyboard','time':1.7},
  {'status':'fail','name':'keyboard','time':3.4},{'status':'fa','name':'mouse','time':1.8},
  {'status':'a','name':'mouse','time':3.5}{'status':'t','name':'typec','time':1.7}]

1 个答案:

答案 0 :(得分:0)

您需要按nametime对其进行排序:

unsorted=[{'status':'f','name':'battery','time':1.3},
{'status':'a','name':'mouse','time':3.5},{'status':'p','name':'battery','time':1.0},
{'status':'p','name':'battery','time':0.8},{'status':'n','name':'touch','time':1.6},
{'status':'t','name':'typec','time':1.7},{'status':'fail','name':'keyboard','time':3.4},
{'status':'fail','name':'keyboard','time':1.7},{'status':'fa','name':'mouse','time':1.8},
{'status':'k','name':'touch','time':2.4}]

sorted(unsorted, key=lambda x: (x['name'], x['time']))

#[{'status': 'p', 'name': 'battery', 'time': 0.8}, {'status': 'p', 'name': 'battery', 'time': 1.0}, {'status': 'f', 'name': 'battery', 'time': 1.3}, {'status': 'fail', 'name': 'keyboard', 'time': 1.7}, {'status': 'fail', 'name': 'keyboard', 'time': 3.4}, {'status': 'fa', 'name': 'mouse', 'time': 1.8}, {'status': 'a', 'name': 'mouse', 'time': 3.5}, {'status': 'n', 'name': 'touch', 'time': 1.6}, {'status': 'k', 'name': 'touch', 'time': 2.4}, {'status': 't', 'name': 'typec', 'time': 1.7}]