Home > Software design >  Sorting and filtering one list based on another
Sorting and filtering one list based on another

Time:06-13

Problem: I would like to sort one list based on another list. Example: below I would like to sort list_sec based on 'key' in this list and the order would be from list_main.

list_main = [3, 33, 2]

list_sec = [{'key': 2, 'rocket': 'mark11'}, {'key': 332, 'rocket': 'mark23'}, {'key': 3, 'rocket': 'mark1'} ]

Output would be as below. (exp: first entry in list_main is 3, so 'key' : 3 should come to index = 0, second value is 33 but this key is missing in list_sec so will discard this. third key is 2, so this will come next.

output = [{'key': 3, 'rocket': 'mark1'}, {'key': 2, 'rocket': 'mark11'}]

I have read couple of answers on similar lines: Python, sort a list by another list , Python 3.x -- sort one list based on another list and then return both lists sorted

But stuck without attempt. Any way this can be done.

CodePudding user response:

Transform your list of dicts into a dict, then you'll be able to retrieve items by value of key.

In [2]: rocket_dict = {item['key']: item for item in list_sec}

In [3]: rocket_dict
Out[3]: 
{2: {'key': 2, 'rocket': 'mark11'},
 332: {'key': 332, 'rocket': 'mark23'},
 3: {'key': 3, 'rocket': 'mark1'}}

If you need a list in that particular order, you can do:

In [4]: output = []

In [5]: for key in list_main:
   ...:     if key in rocket_dict:
   ...:         output.append(rocket_dict[key])
   ...: 

In [6]: output
Out[6]: [{'key': 3, 'rocket': 'mark1'}, {'key': 2, 'rocket': 'mark11'}]

CodePudding user response:

Try this simple method it will work in your case

list_main = [3, 33, 2]

list_sec = [{'key': 2, 'rocket': 'mark11'}, {'key': 332, 'rocket': 'mark23'}, {'key': 3, 'rocket': 'mark1'} ]

sorted_list = [] # The final sorted list
for key in list_main:  # iterate on each key
    for item in list_sec:
        if item['key'] == key: # find the item based on your key
            sorted_list.append(item) # append in sequence
print(sorted_list) # your sorted list

CodePudding user response:

sorted(list(filter(lambda data: data["key"] in list_main, list_sec)),
       key=lambda data: list_main.index(data["key"]))

output:

[{'key': 3, 'rocket': 'mark1'}, {'key': 2, 'rocket': 'mark11'}]

CodePudding user response:

Essentially @LevLevitsky's answer, but with list comprehension

wrap_dict = {item['key']: item for item in list_sec}
output = [wrap_dict[key] for key in list_main if key in wrap_dict]

Or we can use the coolest walrus operator introduced in Python 3.8

output = [rkt_dict for key in list_main if (rkt_dict := wrap_dict.get(key))]
  • Related