Sort json list from another list

陌路散爱 提交于 2021-02-11 13:12:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!