Sort the dict by the key 'ordering' if ordering is greater then that dict should appear first and then the dict which contain next greater ordering and the first three greater ordering dicts should be stored in the list.
Input:
my_list = [{u'item_group': u'Bits Special',
u'item_name': u'Tool Bits-Metric',
u'ordering': 1},
{u'item_group': u'Performance Drills 3X',
u'item_name': u'Drills-Short-Metric',
u'ordering': 3},
{u'item_group': u'Hand Taps',
u'item_name': u'Shank-Metric',
u'ordering': 4},
{u'item_group': u'Tool Bits',
u'item_name': u'T42-Square HSS Tool Bits-BSW',
u'ordering': 2,}]
Expected o/p:
op_list = [{u'item_group': u'Hand Taps',u'item_name': u'Shank-Metric',
u'ordering': 4},{u'item_group': u'Performance Drills 3X',
u'item_name': u'Drills-Short-Metric',u'ordering': 3},
{u'item_group': u'Tool Bits',u'item_name': u'T42-Square HSS
Tool Bits-BSW',u'ordering': 2,}]
I've tried :
for i in mylist:
if i['ordering']>mylist['ordering']:
op_list.append(i)
There are examples showing how to sort a list, giving your own key to use for comparison. You need this revsered (ie descending) and then need to take the top three.
Simplifying what you have, consider
my_list=[{u'ordering':1}, {u'ordering':3}, {u'ordering':4}, {u'ordering':2}]
you can sort this:
>>> sorted(my_list, key=lambda d: d[u'ordering'], reverse=True)
[{'ordering': 4}, {'ordering': 3}, {'ordering': 2}, {'ordering': 1}]
and slice off what you need:
>>> sorted(my_list, key=lambda d: d[u'ordering'], reverse=True)[:3]
[{'ordering': 4}, {'ordering': 3}, {'ordering': 2}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.