原始数据是一个由元组构成的列表,每个元组包含年、月 P 级、数量,要转换成 JSON ,具体示例如下:
# 原始数据 rs=[(2016,1,'p0',1),(2016,2,'p1',2),(2016,2,'p2',3),(2016,3,'p3',25),(2016,4,'p4',55)] # 目标 JSON ,如果某月没有相应的 P 级的数据,要补 0 {'p2': [0, 3, 0, 0], 'p3': [0, 0, 25, 0], 'p0': [1, 0, 0, 0], 'p1': [0, 2, 0, 0], 'p4': [0, 0, 0, 55], 'categories': ['2016-1', '2016-2', '2016-3', '2016-4']} 下面是我的做法,是把数据先转换为 dict ,然后在遍历生成 JSON 的时候通过 setdefault 把缺失的数据补 0 。但是感觉很笨,不知道更好的做法是什么?
# coding=utf-8 rs=[(2016,1,'p0',1),(2016,2,'p1',2),(2016,2,'p2',3),(2016,3,'p3',25),(2016,4,'p4',55)] # 预处理,把 rs 转换为字典 dict1 = {} for (year, month, p_level, count) in rs: dict1.setdefault(year,{}) dict1[year].setdefault(month,{}) dict1[year][month].setdefault(p_level,{}) dict1[year][month][p_level] = count # dict1 >> {2016: {1: {'p0': 1}, 2: {'p2': 3, 'p1': 2}}} # 预处理,取年份月份和 P 级的集合,这样数据有变化也可以处理 p_levels = [] mOnths= [] years = [] for i in rs: if i[0] not in years: years.append(i[0]) if i[1] not in months: months.append(i[1]) if i[2] not in p_levels: p_levels.append(i[2]) months.sort() years.sort() result={} result['categories']=[str(year)+'-'+str(month) for year in years for month in months] for p_level in p_levels: for month in months: result.setdefault(p_level,[]).append(dict1[2016][month].get(p_level, 0)) print result # {'p2': [0, 3, 0, 0], # 'p3': [0, 0, 25, 0], # 'p0': [1, 0, 0, 0], # 'p1': [0, 2, 0, 0], # 'p4': [0, 0, 0, 55], # 'categories': ['2016-1', '2016-2', '2016-3', '2016-4']} 