Home > Mobile >  Rearrange list items by key value Python
Rearrange list items by key value Python

Time:02-15

This is my list.

 my_list1 = [
           {"id":"100", "question_set":"two"},{"qn_id":"101","question_set":"one"},{"qn_id":"102", "question_set":"three"}
    ]

questions_set_first_id_item, questions_set_second_id_item ,questions_set_third_id_item are obtained from database.

questions_set_first_id_item = "one"
questions_set_second_id_item = "two" 
questions_set_third_id_item = "three"

questions_set_first_id_item can be "one" or "two" or "three" and similarly with questions_set_second_id_item and questions_set_thrid_id_item but they cannot be same.

Now list needs to be rearranged questions_set_first_id_item then questions_set_second_id_item and questions_set_third_id_item's values Output required:

my_list1 = [{"qn_id":"101","question_set":"one"},{"id":"100", "question_set":"two"},{"qn_id":"102", "question_set":"three"}
    ]

Another example

questions_set_first_id_item = "three"
questions_set_second_id_item = "two" 
questions_set_third_id_item = "one"

Now list needs to be rearranged questions_set_first_id_item then questions_set_second_id_item and questions_set_third_id_item's values Output required:

my_list1 = [,{"qn_id":"102", "question_set":"three"}, ,{"id":"100", "question_set":"two"}, {"qn_id":"101","question_set":"one"}
        ]

How to rearrange index of list items according to users choice of question_set?

CodePudding user response:

I understand you want to reorder according to a user-given list of question sets. This can be solved with list / dict comprehensions:

expected_order = [questions_set_first_id_item, questions_set_second_id_item, questions_set_third_id_item]
items_by_question_set = {item["question_set"]: item for item in my_list1}
output_list = [items_by_question_set[qs] for qs in expected_order]

This code does not check whether indexes are valid. Look e.g. at the dictionary .get method for this.

  • Related