#-*-encoding:utf-8-*- fromCollectionsImportdefaultdictclassNews (object):def __init__(self, title, type): Self.title=title Self.type=typedef __repr__(self):return "{' title ': '%s ', ' type ':%s}"%(Self.title, self.type) newses=[News (U"Macro Research", 1), News (U"Policy Reports", 1), News (U"Industry Research", 2), News (U"Company Research", 3), News (U"Overseas Information", 3), News (U"other", 1)]#Print newses#{#1: [{' title ': Macro study, ' type ': 1}, {' title ': Policy Report, ' type ': 1}, {' title ': Other, ' type ': 1}],#2: [{' title ': Industry research, ' type ': 2}],#3: [{' title ': Company Research, ' type ': 3}, {' title ': Overseas Information, ' type ': 3}]#}#Method OneD = {} forNinchnewses:ifN.type not inchD:d[n.type]=[] D[n.type].append (n)#Print D#Method TwoD = {} forNinchNewses:d.setdefault (N.type, []). Append (n)#Print D#Method ThreeD =defaultdict (list) forNinchnewses:d[n.type].append (n)#Print D#method FourD =defaultdict (list) map (Lambdan:d[n.type].append (n), newses)#Print D#Method FiveD =defaultdict (list) [D[n.type].append (n) forNinchNewses]#Print D#Output forKeyinchD:Printkey, D[key]Print '==============' forKeyinchD: forValueinchD[key]:PrintKey, ValuePrint '=============='
Python-Grouped dictionaries