1

Full error: 'str' object has no attribute 'match_key'

I am trying to sort a dictionary by the values of one of the keys in the objects but I am running into errors whem doing so. What is the best way to do this kind of sort?

Code:

#part of loop

x = {
    'id': f'{item.id}',
    'post': item,
    'match_key': match_percentage

}

temp_dict.update(x)

sorted_dict = sorted(temp_dict, key=operator.attrgetter('match_key'))
Humza
  • 91
  • 2
  • 9
  • Are you actually trying to sort a list of dictionaries, using a particular key? Because it doesn't make sense to sort a single dictionary by a single key. – Tim Nyborg Mar 25 '21 at 21:28
  • 1
    `sorted_dict = sorted(temp_dict, key=operator.attrgetter(temp_dict['match_key]'))` – Ajay Mar 25 '21 at 21:30
  • im looping to create multiple objects in the dict so yes there will be a lot of objects to sort through @TimNyborg – Humza Mar 25 '21 at 21:30
  • @Ajay when i do that i get error: `attribute name must be a string` – Humza Mar 25 '21 at 21:32
  • https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value – Ajay Mar 25 '21 at 21:34
  • looks like there is a quotes ( ' ' ) mismatch in @Ajay's answer.. sorted_dict = sorted(temp_dict, key=operator.attrgetter(temp_dict['match_key'])) – SANGEETH SUBRAMONIAM Mar 26 '21 at 00:03

1 Answers1

0

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

KyleMit
  • 30,350
  • 66
  • 462
  • 664