If you're looking to sort a list of dictionaries by key, you'll want to use operator.itemgetter
instead like this:
from operator import itemgetter
xs = [
{ 'item': "Apple", 'match_key': 20 },
{ 'item': "Grape", 'match_key': 10 },
{ 'item': "Lemon", 'match_key': 50 }]
sorted_dict = sorted(xs, key=itemgetter('match_key'))
print(sorted_dict)
# [{'item': 'Grape', 'match_key': 10},
# {'item': 'Apple', 'match_key': 20},
# {'item': 'Lemon', 'match_key': 50}]
Explanation
dictionaries
represent collections of items. So values stored in dictionaries are considered items
, not attributes
. This makes sense when we think about how we access values in dictionaries. You use bracket notation []
to access items in a collection, whether by index position or key. But cannot use the dot operator .
to retrieve dictionary values by key, because they are not stored as attributes on the dict.
Further Reading