1

I am getting an unexpected error. I realize that there are posts with similar errors but either could not understand the answer or could not relate it to my case (dictionary).

I am trying to calculate a similarity score for each line of an input file and at every iteration (i.e for each line of input file) store the top 20 values of the score in a dictionary.

Following is my code:

result={}
//code for computation of score for each line of an input file

if (len(result)<20):
    result[str(line)]=score
else:
    if(len(result)==20):
        result = sorted(result.iteritems(), key=operator.itemgetter(1))
        if(result.item()[19].value()<score):
            result.item()[19][str(line)]=score

The error is:

File "retrieve.py", line 45, in <module>
if(result.item()[19].value()<score):
AttributeError: 'list' object has no attribute 'item'
1
  • 1
    There is no item method of either dictionaries or lists. Commented Jun 30, 2013 at 17:56

1 Answer 1

3
result = sorted(result.iteritems(), key=operator.itemgetter(1))

result is not a dictionary anymore.

If I am not mistaken, your problem can be solved this way (assuming lines comes from somewhere):

result = sorted({(calculate_score(line), line) for line in lines})
print(result[:20])

Take a look at OrderedDict for making an ordered dictionary.

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

9 Comments

How else could i sort the dictionary by value, so that i can perform the operaions i want
@naka: there is no way to sort a dictionary: dictionaries don't have an order.
@naka Pass the sorted list result to collections.OrderedDict.
@naka what exactly were you trying to do?
@Elazar : I have an input file, each line of which has a set of words. Next i take a query and compute similarity scores between each line of the input file and the query. I am trying to do this by using dictionary, keeping the maximum size of dictionary as 20(to get top 20 results, if sorted by value)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.