2016-12-20 37 views
3

試圖找出如何按值排序字典列表,其中值以「自定義映射」列表中的字符串開頭。因此,例如,這裏的數據進行排序:Python 3按值排序字典列表,其中值以字符串開頭

'buckets': [ 
    { 
     'doc_count': 23, 
     'key': 'Major League Stuff' 
    }, 
    { 
     'doc_count': 23, 
     'key': 'Football Stuff' 
    }, 
    { 
     'doc_count': 23, 
     'key': 'Football Stuff > Footballs' 
    }, 
    { 
     'doc_count': 23, 
     'key': 'Football Stuff > Footballs > Pro' 
    }, 
    { 
     'doc_count': 22, 
     'key': 'Football Stuff > Footballs > College' 
    }, 
    { 
     'doc_count': 20, 
     'key': 'Football Stuff > Football Stuff Collections > Neat Stuff' 
    }, 
    { 
     'doc_count': 19, 
     'key': 'Football Stuff > Helmets' 
    }, 
    { 
     'doc_count': 4, 
     'key': 'Jewelry' 
    }, 
    { 
     'doc_count': 4, 
     'key': 'Jewelry > Rings' 
    }, 
    { 
     'doc_count': 2, 
     'key': 'All Gifts' 
    }, 
    { 
     'doc_count': 2, 
     'key': 'Gifts for Her' 
    }, 
    { 
     'doc_count': 2, 
     'key': 'Gifts for Her > Jewelry' 
    }, 
    { 
     'doc_count': 2, 
     'key': 'Football Stuff > Footballs > Tykes' 
    }, 
    { 
     'doc_count': 1, 
     'key': 'Brand new items' 
    }, 
    { 
     'doc_count': 1, 
     'key': 'Jewelry > Rings and Bands' 
    } 
    { 
     'doc_count': 1, 
     'key': 'Football Stuff > Footballs > High School' 
    }, 
    { 
     'doc_count': 1, 
     'key': 'Football Stuff > Pads' 
    } 
] 

,我希望它根據此列表進行排序:

sort_map = ['Football Stuff', 
    'Jewelry', 
    'Gifts for Her', 
    'Brand new items', 
    'Major League Stuff', 
    'All Gifts'] 

我有種想「startswith」可以工作,但我不當然如何

buckets = sorted(buckets, key=lambda x: sort_map.index(x['key'].startswith[?])) 

任何幫助讚賞!

附註 - SO是要求我編輯,以解釋爲什麼這篇文章是不同於其他「排序字典值」職位。在發佈之前,我確實看過儘可能多的那些內容,而且沒有涉及匹配字符串部分的內容。所以我確實相信這不是重複的。

+1

的可能的複製[排序按值Python字典(http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value) –

+0

這不是和我解釋了爲什麼在OP – tarponjargon

回答

7

我會充分利用的事實,你可以根據" > "分裂,並採取第一場

buckets = sorted(buckets, key=lambda x: sort_map.index(x['key'].split(" > ")[0])) 

的指數,以提供第二阿爾法標準,你可以返回一個元組與完整的字符串作爲第二個項目,以便它在相同指數的情況下,按字母順序排序:

buckets = sorted(buckets, key=lambda x: (sort_map.index(x['key'].split(" > ")[0]),x['key'])) 
+0

的結尾相當不錯!謝謝! – tarponjargon

0

我認爲這是最好創建一個單獨的函數,而不是lambda,因爲它使代碼更容易理解。

def get_index(x): 
    for i, e in enumerate(sort_map): 
     if x['key'].startswith(e): 
      return i 

buckets = sorted(buckets, key=get_index) 
+0

是的,艱難的選擇之間更短,更具可讀性。感謝您的解決方案。 – tarponjargon