-2

I have an ID list

id = [339, 344, 340, 343, 345, 342, 341]

already select as in the way in this link here, this is the code

mycursor.execute("SELECT * FROM news_tb where id IN ({})".format(",".join([str(i) for i in hasil])))

but the results are in sequence

[(339, '..'), (340, '..'), (341, '..'), (342, '..'), (343, '..'), (344, '..'), (345, '..')]

I want the data output to be sequential according to the id in the list. Thankyou

2 Answers2

1

results = sorted(results, key=lambda x: id.index(x[0]))

lmielke
  • 135
  • 8
0

Assuming your results are in results,

r_dict = dict([r[0],r[1:]] for r in results)
ordered_results = [tuple([i]+list(r_dict[i])) for i in id]
print(ordered_results)

will print the desired list.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101