2 Lists To Sorted Dictionary Back To 2 Lists (multiple Key Values)
Solution 1:
date, Scores = zip(*sorted(zip(date, Scores)))
Solution 2:
Dictionaries do not support multiple copies of identical keys. Your keys should be unique. One way to accomplish this is to make the key a tuple of your dates and scores unless you got the same score on the same day. In which case you could add a third list numbered 0 to 58 and use that as the third element (make it a triple instead of a tuple) as a tiebreaker when sorting.
Solution 3:
Working with lists in this situation might make more sense:
dates = ['2015/07/13', '2015/07/13', '2015/07/07', '2015/07/06']
scores = [9.5, 13.9, 15.5, 12.9]
ldates_scores = zip(dates, scores)
dte = sorted(ldates_scores)
scr = sorted(ldates_scores, key=lambda x: x[1])
print dte
print scr
printfordate,score in dte:
print"Date: %-10s Score: %d" % (date, score)
printfordate,score in scr:
print"Date: %-10s Score: %d" % (date, score)
The output is two lists, sorted first by date (as you are using YYYY/MM/DD), and the second list sorted by score. I have kept the pairs together. The output is as follows:
[('2015/07/06', 12.9), ('2015/07/07', 15.5), ('2015/07/13', 9.5), ('2015/07/13', 13.9)]
[('2015/07/13', 9.5), ('2015/07/06', 12.9), ('2015/07/13', 13.9), ('2015/07/07', 15.5)]
Date: 2015/07/06Score: 12Date: 2015/07/07Score: 15Date: 2015/07/13Score: 9Date: 2015/07/13Score: 13Date: 2015/07/13Score: 9Date: 2015/07/06Score: 12Date: 2015/07/13Score: 13Date: 2015/07/07Score: 15
Solution 4:
The keys in a dict will be unique so you are only capturing a single item for each date. No need for the dict...zip will return a tuple which you then sort.
z = zip(date, Scores)
sorted(z, key=lambda val: val[1], reverse=True)
Post a Comment for "2 Lists To Sorted Dictionary Back To 2 Lists (multiple Key Values)"