我下面有字典列表
[{'balance':'4560.00','totalinwardqty':'4600.00','totaloutwardqty':'40 .00','srno':1,'productname':u'mobile'},
{'balance':'310.00','totalinwardqty':'600.00','totaloutwardqty':'290.00','srno':2,'productname':u'laptop'},
{'balance':'30 .00','totalinwardqty':'502.00','totaloutwardqty':'472.00','srno':3,'productname':u'AC'},
{'balance':'654.00','totalinwardqty':'749.00','totaloutwardqty':'95 .00','srno':4,'productname':u'car'},
{'balance':'100.00','totalinwardqty':'100.00','totaloutwardqty':'0.00','srno':5,'productname':u'tab'},
{'balance':'6000.00','totalinwardqty':'6000.00','totaloutwardqty':'0.00','srno':6,'productname':u'ram'},
{'balance':'500.00','totalinwardqty':'500.00','totaloutwardqty':'0.00','srno':7,'productname':u'arduino'},
{'balance':'80 .00','totalinwardqty':'80 .00','totaloutwardqty':'0.00','srno':8,'productname':u'wifi模块'}]
我想要字典的前五名列表,这些列表按totaloutwardqty的升序排序
答案 0 :(得分:0)
首先,将列表存储在变量中:
lst = [{'balance': '4560.00', 'totalinwardqty': '4600.00', 'totaloutwardqty': '40.00', 'srno': 1, 'productname': u'mobile'},
{'balance': '310.00', 'totalinwardqty': '600.00', 'totaloutwardqty': '290.00', 'srno': 2, 'productname': u'laptop'},
{'balance': '30.00', 'totalinwardqty': '502.00', 'totaloutwardqty': '472.00', 'srno': 3, 'productname': u'AC'},
{'balance': '654.00', 'totalinwardqty': '749.00', 'totaloutwardqty': '95.00', 'srno': 4, 'productname': u'car'},
{'balance': '100.00', 'totalinwardqty': '100.00', 'totaloutwardqty': '0.00', 'srno': 5, 'productname': u'tab'},
{'balance': '6000.00', 'totalinwardqty': '6000.00', 'totaloutwardqty': '0.00', 'srno': 6, 'productname': u'ram'},
{'balance': '500.00', 'totalinwardqty': '500.00', 'totaloutwardqty': '0.00', 'srno': 7, 'productname': u'arduino'},
{'balance': '80.00', 'totalinwardqty': '80.00', 'totaloutwardqty': '0.00', 'srno': 8, 'productname': u'wifi module'}]
然后使用sorted
。
以升序的前5位,我假设您是指totaloutwardqty中的前5位。
sorted(lst,key =lambda x: float(x['totaloutwardqty']))[0:5]
降序:
sorted(lst,key =lambda x: -1*float(x['totaloutwardqty']))[0:5]