2017年5月21日 星期日

[ Python 常見問題 ] Sorting a dict with tuples as values

Source From Here 
Question 
I have a structure that looks like this: 
  1. {'key_info':(rank,raw_data1,raw_data2),'key_info2':....}  
basically i need back a list of the keys in a sorted order, that is sorted based on the specific field in the tuple

How-To 
With help of API:sorted, you can do it this way: 
>>> test_dict = {}
>>> test_dict['John'] = (18, 'Taiwan')
>>> test_dict['Ken'] = (22, 'American')
>>> test_dict['Peter'] = (16, 'Japan')
>>> test_dict['Mary'] = (30, 'China')
>>> test_dict
{'Ken': (22, 'American'), 'John': (18, 'Taiwan'), 'Peter': (16, 'Japan'), 'Mary': (30, 'China')}
>>> sorted(test_dict.keys(), key=lambda k: test_dict[k][0], reverse=True) # Sorting with age in descending order
['Mary', 'Ken', 'John', 'Peter']
>>> sorted(test_dict.keys(), key=lambda k: test_dict[k][1]) # Sorting with country name in ascending order
['Ken', 'Mary', 'Peter', 'John']
>>> test_dict['Winson'] = (29, 'Canada')
>>> test_dict['Jacy'] = (24, 'China')
>>> sorted(test_dict.keys(), key=lambda k: (test_dict[k][1], test_dict[k][0])) # Sorting with country, then age in ascending order
['Ken', 'Winson', 'Jacy', 'Mary', 'Peter', 'John'] # Jacy=(24, 'China'); Mary=(30, 'China')


Supplement 
Python Doc - Sorting HOW TO 
Sort a list by multiple attributes? 

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...