python - Sorting a list of dictionaries based on the order of values of another list -


i'm using python 2.7.3, , i'm trying sort list of dictionaries based on order of values of list.

ie:

listone = ['hazel', 'blue', 'green', 'brown'] listtwo = [{'name': 'steve', 'eyecolor': 'hazel', 'height': '5 ft. 11 inches'},            {'name': 'mark', 'eyecolor': 'brown', 'height': '6 ft. 2 inches'},            {'name': 'mike', 'eyecolor': 'blue', 'height': '6 ft. 0 inches'},            {'name': 'ryan', 'eyecolor': 'brown', 'height': '6 ft, 0 inches'},            {'name': 'amy', 'eyecolor': 'green', 'height': '5 ft, 6 inches'}] 

sorting listtwo based off of order of values in listone, end following:

print listtwo [{'name': 'steve', 'eyecolor': 'hazel', 'height': '5 ft. 11 inches'}, {'name': 'mike', 'eyecolor': 'blue', 'height': '6 ft. 0 inches'}, {'name': 'amy', 'eyecolor': 'green', 'height': '5 ft, 6 inches'}, {'name': 'mark', 'eyecolor': 'brown', 'height': '6 ft. 2 inches'}, {'name': 'ryan', 'eyecolor': 'brown', 'height': '6 ft, 0 inches'}] 

i need output text, i've done display correctly (in correct order) following:

for x in xrange(len(listone)):     y in xrange(len(listtwo)):         if listone[x] == listtwo[y]["eyecolor"]:             print "name: " + str(listtwo[y]["name"]),             print "eye color: " + str(listtwo[y]["eyecolor"]),             print "height: " + str(listtwo[y]["height"]) 

is there sort of lambda expression can used make happen? there has more compact, less complex way of getting in order want.

the simplest way use list.index generate sort value list of dictionaries:

listtwo.sort(key=lambda x: listone.index(x["eyecolor"])) 

this little bit inefficient though, since list.index linear search through eye-color list. if had many eye colors check against, slow. better approach build index dictionary instead:

order_dict = {color: index index, color in enumerate(listone)} listtwo.sort(key=lambda x: order_dict[x["eyecolor"]]) 

if don't want modify listtwo, can use built-in sorted function instead of list.sort method. returns sorted copy of list, rather sorting in-place.


Comments