1 #!/usr/bin/python python 2 # -*-coding=utf-8-*- 3 4 d = [ 5 {'year':2014L,'month':1L,'id':1}, 6 {'year':2014L,'month':2L,'id':2}, 7 {'year':2013L,'month':3L,'id':3}, 8 {'year':2014L,'month':1L,'id':4}, 9 {'year':2013L,'month':1L,'id':5} 10 ] 11 dd = {} 12 for x in d: 13 year = str(x['year']) 14 month = str(x['month']) 15 data = {'id':x['id']} 16 if year in dd: 17 check = True 18 for y in dd[year]: 19 if month in y: 20 check = False 21 y[month].append(data) 22 if check: 23 dd[year].append({month:[data]}) 24 25 else: 26 dd[year]=[{month:[data]}] 27 print dd
测试结果:
~/code/python/test $ python blog.py {'2014': [{'1': [{'id': 1}, {'id': 4}]}, {'2': [{'id': 2}]}], '2013': [{'3': [{'id': 3}]}, {'1': [{'id': 5}]}]}
应该ok了吧
哇,太牛了你。谢谢