python 字典转json的问题

dreambulare 2014-07-17 01:26:08
我现在有个字典
hc = [(76670, 2), (76678, 1), (87559, 1), (89674, 1), (12689, 1), (74718, 1)]
每对为 id,值 对
我现在希望输出json格式是类似{'itemid':76670,'quantity':2}这样的json,除了手动拼接,有没有简便的方法?
...全文
230 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
panghuhu250 2014-07-17
  • 打赏
  • 举报
回复

In [19]: hc = [(76670, 2), (76678, 1), (87559, 1), (89674, 1), (12689, 1), (74718, 1)]

In [20]: import json

In [21]: json1 = json.dumps([{'itemid': v, 'quantity':i} for v, i in hc])

In [22]: json1
Out[22]: '[{"itemid": 76670, "quantity": 2}, {"itemid": 76678, "quantity": 1}, {"itemid": 87559, "quantity": 1}, {"itemid": 89674, "quantity": 1}, {"itemid": 12689, "quantity": 1}, {"itemid": 74718, "quantity": 1}]'
  • 打赏
  • 举报
回复
手动拼下也不复杂吧 特殊的格式必然要特殊的处理方式
The_Third_Wave 2014-07-17
  • 打赏
  • 举报
回复
json库,看一下
  • 打赏
  • 举报
回复
其实还是手动拼接-。-
dreambulare 2014-07-17
  • 打赏
  • 举报
回复
引用 3 楼 panghuhu250 的回复:

In [19]: hc = [(76670, 2), (76678, 1), (87559, 1), (89674, 1), (12689, 1), (74718, 1)]

In [20]: import json

In [21]: json1 = json.dumps([{'itemid': v, 'quantity':i} for v, i in hc])

In [22]: json1
Out[22]: '[{"itemid": 76670, "quantity": 2}, {"itemid": 76678, "quantity": 1}, {"itemid": 87559, "quantity": 1}, {"itemid": 89674, "quantity": 1}, {"itemid": 12689, "quantity": 1}, {"itemid": 74718, "quantity": 1}]'
原来python还能这么用。。。多谢!

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧