Reputation: 31
My dictionaries are from a database but for this example imagine i have two dictionairies
dictionary1 = {
"score": str(percentageScore), #totalScore
"date": str(today), #today
"title": str(title), #title
"timestamp": str(timestamp) #timestamp to display results in order
}
The timestamp is an integer and i would like to use it to sort a python list containing multiple dictionaries like this, in descending order based on the timestamp integer.
I have tried to do this with:
sortedScores = [dictionary1, dictionary2, dictionary3]
for i in range(1, len(sortedScores)):
sortKey = sortedScores[i['timestamp']]
j = (i - 1)
while (j <= 0) and (sortKey < (sortedScores[j])['timestamp']):
sortedScores[j+1] = sortedScores[j]
j -= 1
sortedScores[j+1] = sortKey
However i am currently getting the error
TypeError: 'int' object is not subscriptable
Upvotes: 0
Views: 56
Reputation: 33
The error is in "i['timestamp']" when you write for i in range (1, len(...)), i become an integer between 1 and the other number. So i[timestamp] doesn't have any sense. Try to correct this :)
Upvotes: 0
Reputation: 1397
sortedScores = sorted([dictionary1,dictionary2,dictionary3],key=lambda x:int(x['timestamp']),reverse=True)
Upvotes: 1