Codehai
Codehai

Reputation: 534

sort dicts in list by dict values

I build up a list like that

testList = list()
testList.append('{"_id": "%s", "stuff": "%s", "stuff2": "%s", "stuff3": "%s", "stuff4": "%s"}' % (aList["_id"], aList["stuff"], aCount, anotherList, aList["stuff2"]))

now I want to sort testList's dicts by stuff2 (which contains only numbers as values)

I tried:

import operator
testList.sort(key=operator.itemgetter(2)

and

testList.sort(key=lambda x: x["stuff2"])

and different other solutions I found all over the web :( My list does not sort or I receive

TypeError: string indices must be integers sorting

can someone please tell me what's the problem with this one? Do I build up the dicts wrong or is my sort parameter not right?

Thanks in advance,

Codehai

Upvotes: 1

Views: 146

Answers (2)

rnbguy
rnbguy

Reputation: 1399

You are appending string, not a dictionary.
Do this.

testList = list()
testList.append({"_id": aList["_id"], "stuff": aList["stuff"], "stuff2": aCount, "stuff3": anotherList, "stuff4": aList["stuff2"]})

Upvotes: 3

Joran Beasley
Joran Beasley

Reputation: 113930

your appending a string not a dictionary....you can make it a dictionary using the json library

testList.sort(key=lambda x: json.loads(x)['stuff2'])

Upvotes: 1

Related Questions