问题
I'm trying to sort a json list from another list. example:
jsonList = [{'id': 'das', 'name': 'something'}, {'id': 'rtn', 'name': 'Something Else'}, {'id': 'ddsn', 'name': 'Something ElseElse'}]
orderList = ['rtn', 'ddsn', 'das']
goodList = someFunction(jsonList, orderList )
I need the output to be the json list sorted by the id:
goodList = [{'id': 'rtn', 'name': 'Something Else'}, {'id': 'ddsn', 'name': 'Something ElseElse'}, {'id': 'das', 'name': 'something'}]
回答1:
goodList = sorted(jsonList, key=lambda x: orderList.index(x['id']))
or if you want just sort by id
sorted(jsonList, key=lambda x : x['id'])
来源:https://stackoverflow.com/questions/64814131/sort-json-list-from-another-list