简体   繁体   中英

Sort a list of dicts by multiple keys

I'd like to sort a list of dicts based on the rank of multiple values in the dicts. But the sort returns None as is

Code:

def site_attr_rank(d):
    return attr_rank[d['site']], lang_rank[d['lang']]
attr_rank = {'apple':0, 'pear':1, 'banana':2}
lang_rank = {'a':0, 'b':1, 'c':2}
print 'items 1\n', x['items']
x['items'] = x['items'].sort(key=site_attr_rank)
print 'items 2\n', x['items']

.sort sorts in place and modifies the list. You will want to use x['items'].sort(...) without using the result (which is always None ).

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