0

how to sort a list by the number of elements of another list that is inside dict (Keys of dict are similar with elements of list that should be sorted) .

This is the list I want to sort: list_to_sort = ['a','b','c','d'] This is a dict with the elements: reference_dict = {'a':[1,0,0,1,0], 'b':[1,0,0,0,1,1], 'c':[1,1,1,1,0], 'd':[1,0,0,0,0]}

I should get list_after_sort = ['d','a', 'b', 'c']

SOmething
  • 1
  • 2

2 Answers2

2

Using key in a sorted function gives an ability to pass a function by which the elements would be sorted.

This answer covers useful information.

You can use:

list_to_sort = ['a','b','c','d']
reference_dict = {'a':[1,0,0,1,0], 'b':[1,0,0,0,1,1], 'c':[1,1,1,1,0], 'd':[1,0,0,0,0]}
sorted(list_to_sort, key = lambda x: sum(reference_dict[x]))

# ['d', 'a', 'b', 'c']
Jonas Palačionis
  • 4,591
  • 4
  • 22
  • 55
  • But if instead of [1,1,0,0,0,0] there is ['element', 'element, None, None, None]. What to do in this case ? – SOmething Feb 08 '22 at 13:45
  • 1
    replace the key by `key = lambda x: sum([e is not None for e in reference_dict[x]])` – Jenny Feb 08 '22 at 13:54
1

You can use the key parameter of sorted to pass an arbitrary function.

In this case, get the values from the dictionary and sum them:

list_after_sort = sorted(list_to_sort, key=lambda x: sum(reference_dict[x]))

output: ['d', 'a', 'b', 'c']

using truthy values:
reference_dict = {'a':[1,0,0,'X',0],
                  'b':[1,0,0,0,1,1],
                  'c':[1,1,1,1,0],
                  'd':['element', 'element', None, None, None]}

sorted(list_to_sort, key=lambda x: sum(map(bool, reference_dict[x])))
# ['a', 'd', 'b', 'c']
using blacklist of objects
blacklist = set([0, None, 'None'])

sorted(list_to_sort, key=lambda x: sum(e not in blacklist
                                       for e in reference_dict[x]))
mozway
  • 194,879
  • 13
  • 39
  • 75
  • But if instead of `[1,1,0,0,0,0]` there is `['element', 'element, None, None, None]`. What to do in this case ? – SOmething Feb 08 '22 at 13:45
  • 1
    @SOmething you can convert to booleans to benefit from the truthy values (see update), please make the exact use case more explicit in defining exactly what should be counted and what shouldn't – mozway Feb 08 '22 at 13:47
  • But if None is write like 'None' ? – SOmething Feb 08 '22 at 13:52
  • @SOmething that's why you need to come up with an explicit logic of what should count or not. Can you elaborate in your case? – mozway Feb 08 '22 at 13:54
  • I need to count all elements that aren't 'None'. I don't think I can elaborate – SOmething Feb 08 '22 at 13:56
  • @SOmething check the update, then you should have the logic – mozway Feb 08 '22 at 13:58