How to Sort a List Based on Another List in Python


Here this example demonstrates the method of sorting a list of items based on their properties in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*- 
# ce_sort_example.py
# Sort a list of students based on their scores

# build a dictionary from two lists
def createDict(list1, list2):
	return list2dict(list1, list2)

# print dictionary data
def prinDict(dictName):
	for (k, v) in dictName.items():
		print(k, v)

# sort dictionary
# orderPosition = 0,sort by key;
# orderPosition = 1,sort by value;
def sortedDict(dictName, orderPosition):
	return sorted(dictName.items(), key=lambda d:d[orderPosition], 
	              reverse=True)

# combine two lists to build a dictionary
def list2dict(list1, list2):
	return dict(zip(list1, list2))

def computeMax(dictName):
	return max(dictName.items(), key=lambda x:x[1])

def computeMin(dictName):
	return min(dictName.items(), key=lambda x:x[1])

# format output
def formatTupleOutput(tupleName):
	for item in tupleName:
		print(item[0], item[1])

def main():
	print("----------------------------")
	personList = ["Kelly", "Vicky", "Peter", "John", "Steve"]
	scoreList = [85, 90, 88, 93, 84]

	dict = createDict(personList, scoreList)
	print("Student list:")
	prinDict(dict)
	print("----------------------------")

	print("Student list sorted by score:")
	dictSortedResult = sortedDict(dict, 1)
	formatTupleOutput(dictSortedResult)
	print("----------------------------")

	minValueOfDict = computeMin(dict)
	print("The student with the lowest score: ")
	print(minValueOfDict[0], minValueOfDict[1])
	print("----------------------------")

	maxValueOfDict = computeMax(dict)
	print("The student with the highest score: ")
	print(maxValueOfDict[0], maxValueOfDict[1])
	print("----------------------------")	

if __name__ == '__main__':
	main()

After running the codes above, we can get these results:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments