如何通过特定键任意排序一系列dicts?

时间:2016-04-25 14:21:06

标签: python json sorting

如何根据任意顺序按list dict个值namedict 720p进行排序?我希望名为dict的{​​{1}}首先出现,然后1080p名称为dict,最后360p名称为hosters = [] for entry in json.loads(aResult[1][0]): if 'file' not in entry or 'label' not in entry: continue sLabel = sName + ' - ' + entry['label'].encode('utf-8') hoster = dict() hoster['link'] = entry['file'] hoster['name'] = sLabel hoster['resolveable'] = True hosters.append(hoster) public class MyClass { private bool initialized = false; public void Initialize() { if(!initialized) { //Install Database tables initialized = true; } } public void DoSomething() { //Some code which depends on the database tables being created } public void DoSomethingElse() { //Some other code which depends on the database tables being created } }

{{1}}

1 个答案:

答案 0 :(得分:0)

您将需要使用自定义排序功能。这样的事情应该有效:

def sort_by_resolution(hoster):
    desired_order = ['720p', '1080p', '360p']
    if hoster['name'] in desired_order:
        return desired_order.index(hoster['name'])
    else:
        return len(desired_order)

sorted(foo, key=sort_by_resolution)
# [{'name': '720p'}, {'name': '1080p'}, {'name': '360p'}]