0

I have a tuple list in which i want to sort according to the order specified in another list. This is the list to be sorted:

Start_Keyword=[(u'NUMBER', u'two', u'2.0', [1]), (u'RND', u'random', u'random', [8])]

The required output is :

Start_Keyword=[(u'RND', u'random', u'random', [8]),(u'NUMBER', u'two', u'2.0', [1])] 

What i did is defined an order and sorted according to the index of it:

predefined_list = ['PROB','RND','NUMBER']
ordering = {word: i for i, word in enumerate(predefined_list)}
print sorted(Start_Keyword, key=lambda x: ordering.get)

But i am getting the following error:

 print sorted(Start_Keyword2, key=ordering.get)
 TypeError: unhashable type: 'list'

please can anyone help on this?

1
  • not with this code. Commented Jan 2, 2017 at 11:58

2 Answers 2

2

this is one way to get that working:

lst = sorted(Start_Keyword, key=lambda x: predefined_list.index(x[0]))
print(lst)

use the index in predefined_list as sort criterion.

you seem to use python2; in python3 the error message for your version is a bit clearer:

TypeError: unorderable types: 
    builtin_function_or_method() < builtin_function_or_method()

you try to compare the get method (without arguments) of dict. they are indeed unorderable.

Sign up to request clarification or add additional context in comments.

Comments

1
predefined_list = ['PROB','RND','NUMBER']
Start_Keyword=[(u'NUMBER', u'two', u'2.0', [1]), (u'RND', u'random', u'random', [8])]    

order = {word:index for index, word in enumerate(predefined_list)}
Start_Keyword.sort(key=lambda x: order.get(x[0]) )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.