I have the following data and following function that works to sort the products to the front of the list that match the specified category.
products =[{'t1': 'bbq', 'category': 2}, {'name': 't5', 'category': 3}, {'name': 't6', 'category': 3}, {'name': 't2', 'category': 2}, {'name': 't3', 'category': 2}, {'name': 't4', 'category': 1}, {'name': 't7', 'category': 1}]
category = 2
I found I have to run this function twice in order to actually get this accomplished, why? How do I need to modify the function to just have to run this once? I am trying to modify products inplace via the category sorted as specified.
def sort_by_cat(products,category):
for p in products:
print(p)
if p['category']==category:
continue
else:
products.append(products.pop(products.index(p)))
return
sort_by_cat(products,category)
sort_by_cat(products,category)
Desired output:
[{'name': 't1', 'category': 2},
{'name': 't2', 'category': 2},
{'name': 't3', 'category': 2},
{'name': 't4', 'category': 1},
{'name': 't5', 'category': 3},
{'name': 't6', 'category': 3},
{'name': 't7', 'category': 1}]