Python处理Dict生成json
问题描述
情况是这样:json文件中存在一个值为
'headers':{ 'connection':['close'], 'content_language':['en'], 'content_length':['3137'], 'content_type':['text/html'], 'server':['squid/3.1.23'], 'unknown':[ {'key':'mime_version','value':['1.0']}, {'key':'date','value':['Sat, 25 Mar 2017 06:11:38 GMT']}, {'key':'x_squid_error','value':['ERR_INVALID_URL 0']}, {'key':'x_cache','value':['MISS from unknown']}, {'key':'x_cache_lookup','value':['NONE from unknown:8080']} ]}
由于之前的脚本的处理过于简单粗暴。现实要将'unknown'给替换成字典中的值。以下是我处理的一段Test code ,在Ipython中:
import jsonf = open(’file.json’,’r’)test_line = f.readline()jsonstr = json.loads(test_line)he = jsonstr[’headers’]# 输出正常的for (k,v) in he.items(): print k,’:’,v[0]
输出的是:
'connection':'close', 'content_language':'en', 'content_length':'3137', 'content_type':'text/html', 'server':'squid/3.1.23', 'unknown':[ {'value':['1.0'],'key':'mime_version'}
问题:1, 怎么处理“unknown”中的list,用for的话,怎么输出?2, 怎么处理“unknown”使其能输出如下的结果:
'connection':'close', 'content_language':'en', 'content_length':'3137', 'content_type':'text/html', 'server':'squid/3.1.23', 'mime_version':'1.0', 'date':'Sat, 25 Mar 2017 06:11:38 GMT', 'x_squid_error':'ERR_INVALID_URL 0', 'x_cache':'MISS from unknown', 'x_cache_lookup':'NONE from unknown:8080'
谢谢!~
问题解答
回答1:# 无非就是list套dict,一层一层往下写就是了# 输出正常的for (k,v) in he.items(): if k != ’unknown’:print k,’:’,v[0] else:# unknown对应的值是listfor it in v: # it是dict print it.get(’key’), ’:’, it.get(’value’)[0]回答2:
要学会优雅的处理数据,只要把unknown 取出来再合并进去就行了。
unknown = headers[’unknown’]headers.pop(’unknown’)set(map(lambda x: (x[’key’], x[’value’][0])))headers = dict(headers.items() + unknown)回答3:
headers.update({_[’key’]: _[’value’][0] for _ in headers[’unknown’]})headers.pop(’unknown’)print headers
相关文章:
1. javascript - 读js权威指南“作为值得函数”产生了疑惑,求释疑2. 请问带渐变背景的进度条如何实现?求给点思路3. python3.x - python中的虚拟环境怎样设置一直处于激活状态4. javascript - 为什么 process.stdin 会有 write 方法◔ ‸◔?5. boostrap怎么在移动端不显示sidebar?6. python中merge后文件莫名变得非常大7. file - Python如何读文件内容修改后写回原文件8. android - 使用listview加载不同item,数据填充错误。9. HTML5禁止img预览该怎么解决?10. java - 怎么处理前台要展示,但是数据库表没有该字段的实体类冗余属性呢?