2017-05-05 79 views
-1

我有包含的值如下一個字典A中的一對錶A的值列表的:排序其中containes對值基於列表B的值(鍵,值),其是

dict_A ={"George Washington":{ 
'lname':'Washinghton', 
'fname':'George', 
'class_id':'math', 
'teacher':'John Doe', 
'end_year_score' : 8} 

我轉換成列表的

​​

我List_A現在是這樣的:

[(George Washington', {, u'fname': 'George', u'class_id' : 'math', u'teacher' : 'John Doe', u'end_year_score' : 8})] 

新編輯List_B

List_B = [(George Washington', {, u'fname': 'George', u'lname': 'Washington' u'class_id' : 'math', u'teacher' : 'John Doe', u'end_year_score' : 8}), (Genghis Khan', {u'fname': 'Genghis ', u'lname':'Khan', u'class_id' : 'math', u'teacher' : 'John Doe', u'end_year_score' : 6}), ('Queen Victoria', {u'fname': 'Queen', u'lname':'Victoria', u'class_id' : 'math', u'teacher' : 'John Doe', u'end_year_score' : 5}), etc...,] 

的例子,但就像我說我有一個List_B作爲對我的List_A的價值。

現在讓我們說我想根據我的List_B的end_year_score的數值對我的List_A進行排序。我會怎麼做?

我已經試過這樣:

List_A.sort(key=lambda x: x[4]) >>> IndexError: tuple index out of range 
List_A.sort(key=lambda x: x[1,4]) >>> TypeError: tuple indices must be integers, not tuple 
List_A.sort(key=lambda x: x[1]['end_year_score') >>> TypeError: unhashable type: 'dict' 

它實際上是可能的嗎?

+0

對不起,什麼是List_B?但請注意,您提供的第三種語法是正確的,適用於您提供的數據。 –

+1

'Michel PAULIN'從哪裏來? c –

回答

2

你的元組有一個字符串和字典

這是你可以怎麼做

List_A.sort(cmp = lambda x,y:cmp(x[1]['end_year_score'],y[1]['end_year_score'])) 
+0

謝謝你的工作:) – glaziko

+0

@glaziko隨時準備提供幫助,請接受答案爲正確答案 –