values = [11,22,33,44,55,66,77,88,99,110] mydict = {} for value in values: if value > 66: if mydict.has_key('k1'): mydict['k1'].append(value) else: mydict['k1'] = [value] else: if mydict.has_key('k2'): mydict['k2'].append(value) else: mydict['k2'] = [value]
print (mydict)
方法2:默认字典
from collections import defaultdict values = [11,22,33,44,55,66,77,88,99,110] mydict = defaultdict(list) for value in values: if value > 66: mydict['k1'].append(value) else: mydict['k2'].append(value) print (mydict)