按键总和对字典列表排序

时间:2015-03-20 13:57:59

标签: python list sorting dictionary sum

我希望通过读取总和在python中对以下列表进行排序。

[{'news': [{'url': 'www.apple.com', 'reads': 100}], 'stock': 'AAPL'}, {'news': [{'url': 'www.google.com', 'reads': 75}, {'url': 'news.google.com', 'reads': 75}], 'stock': 'GOOG'}]

即。此列表应按如下方式排序

[{'news': [{'url': 'www.google.com', 'reads': 75}, {'url': 'news.google.com', 'reads': 75}], 'stock': 'GOOG'}, {'news': [{'url': 'www.apple.com', 'reads': 100}], 'stock': 'AAPL'}]

请帮忙。

2 个答案:

答案 0 :(得分:4)

与往常一样,您可以使用自定义键功能对对象进行排序:

def sum_of_reads(ob):
    return sum(d['reads'] for d in ob['news'])

sorted(input_list, key=sum_of_reads, reverse=True)

或内联为lambda:

sorted(input_list, key=lambda o: sum(d['reads'] for d in o['news']), reverse=True)

演示:

>>> from pprint import pprint
>>> input_list = [{'news': [{'url': 'www.apple.com', 'reads': 100}], 'stock': 'AAPL'}, {'news': [{'url': 'www.google.com', 'reads': 75}, {'url': 'news.google.com', 'reads': 75}], 'stock': 'GOOG'}]
>>> pprint(sorted(input_list, key=lambda o: sum(d['reads'] for d in o['news']), reverse=True))
[{'news': [{'reads': 75, 'url': 'www.google.com'},
           {'reads': 75, 'url': 'news.google.com'}],
  'stock': 'GOOG'},
 {'news': [{'reads': 100, 'url': 'www.apple.com'}], 'stock': 'AAPL'}]

答案 1 :(得分:0)

你可以这样做。

x = [{'news': [{'url': 'www.apple.com', 'reads': 100}], 'stock': 'AAPL'}, {'news': [{'url': 'www.google.com', 'reads': 75}, {'url': 'news.google.com', 'reads': 75}], 'stock': 'GOOG'}]
x.sort()
print x

将打印:

[{'news': [{'url': 'www.google.com', 'reads': 75}, {'url': 'news.google.com', 'reads': 75}], 'stock': 'GOOG'}, {'news': [{'url': 'www.apple.com', 'reads': 100}], 'stock': 'AAPL'}]