python把元组变成列表_Python | 包含元组的列表转 JSON,更好的做法?

原始数据是一个由元组构成的列表,每个元组包含年、月、 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']}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值