简体   繁体   中英

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

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"]})

你附加一个字符串而不是一个字典....你可以使用json库使它成为一个字典

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM