Skip to content Skip to sidebar Skip to footer

Sorting A List Of Dictionaries Based On The Order Of Values Of Another List

I'm using python 2.7.3, and I'm trying to sort a list of dictionaries based on the order of values of another list. IE: listOne = ['hazel', 'blue', 'green', 'brown'] listTwo = [{'n

Solution 1:

The simplest way would be to use list.index to generate a sort value for your list of dictionaries:

listTwo.sort(key=lambda x: listOne.index(x["eyecolor"]))

This is a little bit inefficient though, since list.index does a linear search through the eye-color list. If you had many eye colors to check against, it would be slow. A somewhat better approach would build an index dictionary instead:

order_dict = {color: indexforindex, color in enumerate(listOne)}
listTwo.sort(key=lambda x: order_dict[x["eyecolor"]])

If you don't want to modify listTwo, you can use the built-in sorted function instead of the list.sort method. It returns a sorted copy of the list, rather than sorting in-place.

Solution 2:

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'}]


order_list_dict = {color: index for index, color inenumerate(listOne)}


print(order_list_dict)

print(sorted(listTwo, key=lambda i: order_list_dict[i["eyecolor"]]))

Post a Comment for "Sorting A List Of Dictionaries Based On The Order Of Values Of Another List"