python可分组字典

# -*- encoding: UTF-8 -*-
from collections import defaultdict

class News(object):
    def __init__(self, title, type):
        self.title =title
        self.type = type

    def __repr__(self):
        return "{'title':'%s', 'type':%s}"%(self.title, self.type)


newses = [
      News(u"宏观研究", 1), 
      News(u"策略报告", 1), 
      News(u"行业研究", 2), 
      News(u"公司研究", 3), 
      News(u"海外资讯", 3), 
      News(u"其他", 1)
]
#print newses 

#{
#   1: [{'title':宏观研究, 'type':1}, {'title':策略报告, 'type':1}, {'title':其他, 'type':1}], 
#   2: [{'title':行业研究, 'type':2}], 
#   3: [{'title':公司研究, 'type':3}, {'title':海外资讯, 'type':3}]
#}

#方法一
d = {}
for n in newses:
    if n.type not in d:
        d[n.type] = []
    d[n.type].append(n)
#print d

#方法二
d = {}
for n in newses:
    d.setdefault(n.type, []).append(n)
#print d

#方法三
d = defaultdict(list)
for n in newses:
    d[n.type].append(n)
#print d

#方法四
d = defaultdict(list)
map(lambda n:d[n.type].append(n),newses)
#print d

#方法五
d = defaultdict(list)
[d[n.type].append(n) for n in newses]
#print d

#输出
for key in d:
    print key, d[key]
    
print '=============='
for key in d:
    for value in d[key]:
        print key, value
    print '=============='
原文地址:https://www.cnblogs.com/linjiqin/p/4283648.html