I have a simple dictionary and a list which i would like to sort by the values in my dictionary.
data_dict = {'foo' : 'one', 'bar' : 'two', 'foobar' : 'three', 'notinsort' : 'four'}
custom_sort = ['three','one','two']
my own attempt has been to use a dictionary comprehension with a custom key in the sort:
{k:v for k,v in sorted(data_dict.items(), key=lambda i : custom_sort.index(i[1]) )}
which will rightly return a ValueError: 'four' is not in list
no problem, I can filter this out with an if-else statement within the lambda? as I still want the values to be sorted initially by my custom sort then a natural sort will do.
{
k: v
for k, v in sorted(
data_dict.items(),
key=lambda i: custom_sort.index(i[1])
if [k for k in data_dict.values() if k in custom_sort]
else sorted(data_dict.items()),
)
}
this returns the same ValueError, any variations I've tried on this will end up giving me a natural sort ignoring my custom key.
my desired output from the input above is :
data_dict = {'foobar' : 'three', 'foo' : 'one', 'bar' : 'two', 'notinsort' : 'four'}
I've had a the following questions :
How do I sort a dictionary by value? & Custom Sorting Python Dictionary
but wasn't able to come to an answer.