nish
nish

Reputation: 7280

python dictionary error AttributeError: 'list' object has no attribute 'item'

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'

Upvotes: 1

Views: 20362

Answers (1)

Elazar
Elazar

Reputation: 21605

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.

Upvotes: 3

Related Questions