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'))
6
  • 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. Commented Mar 25, 2021 at 21:28
  • 1
    sorted_dict = sorted(temp_dict, key=operator.attrgetter(temp_dict['match_key]')) Commented Mar 25, 2021 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 Commented Mar 25, 2021 at 21:30
  • @Ajay when i do that i get error: attribute name must be a string Commented Mar 25, 2021 at 21:32
  • stackoverflow.com/questions/613183/… Commented Mar 25, 2021 at 21:34

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.