Home > Mobile >  How to sort a list by the number of items in another list that is inside dict, with keys similar to
How to sort a list by the number of items in another list that is inside dict, with keys similar to

Time:02-08

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']

CodePudding user response:

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']

CodePudding user response:

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']

  •  Tags:  
  • Related